Make OrderedHash#to_a preserve order

This commit is contained in:
Christos Trochalakis 2010-02-12 11:29:19 +02:00 committed by Kyle Banker
parent 16ea148ab1
commit 83f2bdf472
2 changed files with 9 additions and 0 deletions

View File

@ -71,6 +71,11 @@ class OrderedHash < Hash
end end
alias :each_pair :each alias :each_pair :each
def to_a
@ordered_keys ||= []
@ordered_keys.map { |k| [k, self[k]] }
end
def values def values
collect { |k, v| v } collect { |k, v| v }
end end

View File

@ -76,6 +76,10 @@ class OrderedHashTest < Test::Unit::TestCase
assert_equal @ordered_keys, @oh.keys assert_equal @ordered_keys, @oh.keys
end end
def test_to_a_order_preserved
assert_equal @ordered_keys, @oh.to_a.map(&:first)
end
def test_order_preserved_after_replace def test_order_preserved_after_replace
@oh['a'] = 42 @oh['a'] = 42
assert_equal @ordered_keys, @oh.keys assert_equal @ordered_keys, @oh.keys