Skip to content

Commit

Permalink
Hash sub class creates new sub class objects instead of Hash
Browse files Browse the repository at this point in the history
  • Loading branch information
kou committed Mar 21, 2017
1 parent 3703aed commit e72e50b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 4 additions & 4 deletions mrbgems/mruby-hash-ext/mrblib/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ def self.[](*object)
if length == 1
o = object[0]
if o.respond_to?(:to_hash)
h = Hash.new
h = self.new
object[0].to_hash.each { |k, v| h[k] = v }
return h
elsif o.respond_to?(:to_a)
h = Hash.new
h = self.new
o.to_a.each do |i|
raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a)
k, v = nil
Expand All @@ -53,7 +53,7 @@ def self.[](*object)
unless length % 2 == 0
raise ArgumentError, 'odd number of arguments for Hash'
end
h = Hash.new
h = self.new
0.step(length - 2, 2) do |i|
h[object[i]] = object[i + 1]
end
Expand Down Expand Up @@ -211,7 +211,7 @@ def flatten(level=1)
#

def invert
h = Hash.new
h = self.class.new
self.each {|k, v| h[v] = k }
h
end
Expand Down
12 changes: 12 additions & 0 deletions mrbgems/mruby-hash-ext/test/hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@
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_nil Hash.try_convert(nil)
assert_nil Hash.try_convert("{1=>2}")
Expand Down Expand Up @@ -143,6 +149,12 @@
assert_equal('b', h[2])
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
h = { 1 => 2, 3 => 4, 5 => 6 }
assert_equal({3=>4,5=>6}, h.keep_if {|k, v| k + v >= 7 })
Expand Down

0 comments on commit e72e50b

Please sign in to comment.