From e6c5c08c18f5f114924e5e863dfc63d099b9cfc6 Mon Sep 17 00:00:00 2001 From: chaitanyav Date: Sat, 26 Jun 2010 01:52:20 -0700 Subject: [PATCH] Add OrderedHash#invert to preserve order in ruby 1.8 --- activesupport/lib/active_support/ordered_hash.rb | 4 ++++ activesupport/test/ordered_hash_test.rb | 6 ++++++ 2 files changed, 10 insertions(+), 0 deletions(-) diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index a19d6c3..6b563b9 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 dca5c5d..0f11e59 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -250,4 +250,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 -- 1.7.1