Commit 41f5c5b2 authored by Yukihiro "Matz" Matsumoto's avatar Yukihiro "Matz" Matsumoto Committed by GitHub

Merge pull request #3529 from kou/hash-ext-sub-class

Hash sub class creates new sub class objects instead of Hash
parents 8ca98231 e72e50b5
...@@ -28,11 +28,11 @@ class Hash ...@@ -28,11 +28,11 @@ class Hash
if length == 1 if length == 1
o = object[0] o = object[0]
if o.respond_to?(:to_hash) if o.respond_to?(:to_hash)
h = Hash.new h = self.new
object[0].to_hash.each { |k, v| h[k] = v } object[0].to_hash.each { |k, v| h[k] = v }
return h return h
elsif o.respond_to?(:to_a) elsif o.respond_to?(:to_a)
h = Hash.new h = self.new
o.to_a.each do |i| o.to_a.each do |i|
raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a) raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a)
k, v = nil k, v = nil
...@@ -53,7 +53,7 @@ class Hash ...@@ -53,7 +53,7 @@ class Hash
unless length % 2 == 0 unless length % 2 == 0
raise ArgumentError, 'odd number of arguments for Hash' raise ArgumentError, 'odd number of arguments for Hash'
end end
h = Hash.new h = self.new
0.step(length - 2, 2) do |i| 0.step(length - 2, 2) do |i|
h[object[i]] = object[i + 1] h[object[i]] = object[i + 1]
end end
...@@ -211,7 +211,7 @@ class Hash ...@@ -211,7 +211,7 @@ class Hash
# #
def invert def invert
h = Hash.new h = self.class.new
self.each {|k, v| h[v] = k } self.each {|k, v| h[v] = k }
h h
end end
......
...@@ -39,6 +39,12 @@ assert('Hash.[] "c_key", "c_value"') do ...@@ -39,6 +39,12 @@ assert('Hash.[] "c_key", "c_value"') do
end end
end end
assert('Hash.[] for sub class') do
sub_hash_class = Class.new(Hash)
sub_hash = sub_hash_class[]
assert_equal(sub_hash_class, sub_hash.class)
end
assert('Hash.try_convert') do assert('Hash.try_convert') do
assert_nil Hash.try_convert(nil) assert_nil Hash.try_convert(nil)
assert_nil Hash.try_convert("{1=>2}") assert_nil Hash.try_convert("{1=>2}")
...@@ -143,6 +149,12 @@ assert("Hash#invert") do ...@@ -143,6 +149,12 @@ assert("Hash#invert") do
assert_equal('b', h[2]) assert_equal('b', h[2])
end end
assert("Hash#invert with sub class") do
sub_hash_class = Class.new(Hash)
sub_hash = sub_hash_class.new
assert_equal(sub_hash_class, sub_hash.invert.class)
end
assert("Hash#keep_if") do assert("Hash#keep_if") do
h = { 1 => 2, 3 => 4, 5 => 6 } h = { 1 => 2, 3 => 4, 5 => 6 }
assert_equal({3=>4,5=>6}, h.keep_if {|k, v| k + v >= 7 }) assert_equal({3=>4,5=>6}, h.keep_if {|k, v| k + v >= 7 })
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment