From 449cf50d858c9a1f7cc9fcae3ad02841da0440be 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 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(+) diff --git a/activesupport/lib/active_support/ordered_hash.rb b/activesupport/lib/active_support/ordered_hash.rb index ee34e2e7c3..544541205d 100644 --- a/activesupport/lib/active_support/ordered_hash.rb +++ b/activesupport/lib/active_support/ordered_hash.rb @@ -147,6 +147,10 @@ def replace(other) 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 eaa59605be..47c863e903 100644 --- a/activesupport/test/ordered_hash_test.rb +++ b/activesupport/test/ordered_hash_test.rb @@ -228,4 +228,10 @@ def test_update_sets_keys @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 -- GitLab