diff options
| author | Kouhei Sutou <[email protected]> | 2017-03-21 16:42:25 +0900 |
|---|---|---|
| committer | Kouhei Sutou <[email protected]> | 2017-03-21 23:25:36 +0900 |
| commit | e72e50b5d57d4ad003da8a1531263f7795c27db5 (patch) | |
| tree | 01cc3d00b73e7e0b2819e339f6a7dff24a260b2b /mrbgems/mruby-hash-ext | |
| parent | 3703aed7ab7c056ef7a58fd8d25b84b59f715dad (diff) | |
| download | mruby-e72e50b5d57d4ad003da8a1531263f7795c27db5.tar.gz mruby-e72e50b5d57d4ad003da8a1531263f7795c27db5.zip | |
Hash sub class creates new sub class objects instead of Hash
Diffstat (limited to 'mrbgems/mruby-hash-ext')
| -rw-r--r-- | mrbgems/mruby-hash-ext/mrblib/hash.rb | 8 | ||||
| -rw-r--r-- | mrbgems/mruby-hash-ext/test/hash.rb | 12 |
2 files changed, 16 insertions, 4 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb index db4db42e8..31ff6d685 100644 --- a/mrbgems/mruby-hash-ext/mrblib/hash.rb +++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb @@ -28,11 +28,11 @@ class Hash 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 @@ -53,7 +53,7 @@ class Hash 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 @@ -211,7 +211,7 @@ class Hash # def invert - h = Hash.new + h = self.class.new self.each {|k, v| h[v] = k } h end diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb index b43541b7f..6e70953f5 100644 --- a/mrbgems/mruby-hash-ext/test/hash.rb +++ b/mrbgems/mruby-hash-ext/test/hash.rb @@ -39,6 +39,12 @@ assert('Hash.[] "c_key", "c_value"') do 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}") @@ -143,6 +149,12 @@ assert("Hash#invert") do 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 }) |
