add OrderedHash[] initialization
This commit is contained in:
parent
73233d6589
commit
7e0a1b9721
|
@ -32,9 +32,28 @@ class OrderedHash < Hash
|
|||
|
||||
# We only need the body of this class if the RUBY_VERSION is before 1.9
|
||||
if RUBY_VERSION < '1.9'
|
||||
|
||||
attr_accessor :ordered_keys
|
||||
|
||||
def self.[] *args
|
||||
oh = OrderedHash.new
|
||||
if Hash === args[0]
|
||||
oh.merge! args[0]
|
||||
elsif (args.size % 2) != 0
|
||||
raise ArgumentError, "odd number of elements for Hash"
|
||||
else
|
||||
0.step(args.size - 1, 2) do |key|
|
||||
value = key + 1
|
||||
oh[args[key]] = args[value]
|
||||
end
|
||||
end
|
||||
oh
|
||||
end
|
||||
|
||||
def initialize(*a, &b)
|
||||
super
|
||||
@ordered_keys = []
|
||||
end
|
||||
|
||||
def keys
|
||||
@ordered_keys || []
|
||||
end
|
||||
|
@ -90,7 +109,5 @@ class OrderedHash < Hash
|
|||
super
|
||||
@ordered_keys = []
|
||||
end
|
||||
|
||||
end # Ruby before 1.9
|
||||
|
||||
end
|
||||
end
|
||||
|
|
|
@ -53,6 +53,10 @@ class DBAPITest < Test::Unit::TestCase
|
|||
|
||||
oid = @@coll.save(oh)
|
||||
assert_equal 'foo', @@coll.find_first(:_id => oid)['b']
|
||||
|
||||
oh = OrderedHash['a' => 1, 'b' => 'foo']
|
||||
oid = @@coll.save(oh)
|
||||
assert_equal 'foo', @@coll.find_first(:_id => oid)['b']
|
||||
end
|
||||
|
||||
def test_insert_multiple
|
||||
|
|
|
@ -12,6 +12,15 @@ class OrderedHashTest < Test::Unit::TestCase
|
|||
@ordered_keys = %w(c a z)
|
||||
end
|
||||
|
||||
def test_initialize
|
||||
a = OrderedHash.new
|
||||
a['x'] = 1
|
||||
a['y'] = 2
|
||||
|
||||
b = OrderedHash['x' => 1, 'y' => 2]
|
||||
assert_equal a, b
|
||||
end
|
||||
|
||||
def test_empty
|
||||
assert_equal [], OrderedHash.new.keys
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue