From 83f2bdf472b3a234ae7a249ad5b09c0e427d83df Mon Sep 17 00:00:00 2001 From: Christos Trochalakis Date: Fri, 12 Feb 2010 11:29:19 +0200 Subject: [PATCH] Make OrderedHash#to_a preserve order --- lib/mongo/util/ordered_hash.rb | 5 +++++ test/test_ordered_hash.rb | 4 ++++ 2 files changed, 9 insertions(+) diff --git a/lib/mongo/util/ordered_hash.rb b/lib/mongo/util/ordered_hash.rb index ca849ac..63fe14d 100644 --- a/lib/mongo/util/ordered_hash.rb +++ b/lib/mongo/util/ordered_hash.rb @@ -71,6 +71,11 @@ class OrderedHash < Hash end alias :each_pair :each + def to_a + @ordered_keys ||= [] + @ordered_keys.map { |k| [k, self[k]] } + end + def values collect { |k, v| v } end diff --git a/test/test_ordered_hash.rb b/test/test_ordered_hash.rb index 08c957b..90be0a1 100644 --- a/test/test_ordered_hash.rb +++ b/test/test_ordered_hash.rb @@ -76,6 +76,10 @@ class OrderedHashTest < Test::Unit::TestCase assert_equal @ordered_keys, @oh.keys end + def test_to_a_order_preserved + assert_equal @ordered_keys, @oh.to_a.map(&:first) + end + def test_order_preserved_after_replace @oh['a'] = 42 assert_equal @ordered_keys, @oh.keys