From 9958950f78638e4a6c6800404d84f22effc0748e Mon Sep 17 00:00:00 2001 From: chaitanyav Date: Sat, 26 Jun 2010 01:52:20 -0700 Subject: Add OrderedHash#invert to preserve order in ruby 1.8 [#4875] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activesupport/lib/active_support/ordered_hash.rb | 4 ++++ activesupport/test/ordered_hash_test.rb | 6 ++++++ 2 files changed, 10 insertions(+) (limited to 'activesupport') diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index a19d6c3532..6b563b9063 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -162,6 +162,10 @@ module ActiveSupport self end + def invert + OrderedHash[self.to_a.map!{|key_value_pair| key_value_pair.reverse}] + end + def inspect "#" end diff --git a/activesupport/test/ordered_hash_test.rb b/activesupport/test/ordered_hash_test.rb index f3d2ec0286..fc467b41de 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -257,4 +257,10 @@ class OrderedHashTest < Test::Unit::TestCase @updated_ordered_hash.update(:name => "Bob") assert_equal [:name], @updated_ordered_hash.keys end + + def test_invert + @ordered_hash = ActiveSupport::OrderedHash[[["foo", "FOO"], ["bar", "BAR"]]] + @inverted_ordered_hash = @ordered_hash.invert + assert_equal [["FOO", "foo"], ["BAR", "bar"]], @inverted_ordered_hash.to_a + end end -- cgit v1.2.3