summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-hash-ext
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2014-09-19 01:14:50 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2014-09-19 01:14:50 +0900
commit50f54529f25c688c83cd8a281d415f3dc2314184 (patch)
treeb0c19f4c696eec71dcd680a209ceb1856a5dc99e /mrbgems/mruby-hash-ext
parent02b2ac8de2ea12b97bc80aab0d582cda4634e71c (diff)
downloadmruby-50f54529f25c688c83cd8a281d415f3dc2314184.tar.gz
mruby-50f54529f25c688c83cd8a281d415f3dc2314184.zip
to_hash/to_a check in Hash[] should only be done when only one argument is given; ref #2594
Diffstat (limited to 'mrbgems/mruby-hash-ext')
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb49
1 files changed, 27 insertions, 22 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index f214cb1d5..ea5e6bc1b 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -24,32 +24,37 @@ class Hash
#
def self.[](*object)
- o = object[0]
- if o.respond_to?(:to_hash)
- h = Hash.new
- object[0].to_hash.each { |k, v| h[k] = v }
- return h
- elsif o.respond_to?(:to_a)
- h = Hash.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
- case i.size
- when 2
- k = i[0]
- v = i[1]
- when 1
- k = i[0]
- else
- raise ArgumentError, "invalid number of elements (#{i.size} for 1..2)"
+ length = object.length
+ if length == 1
+ o = object[0]
+ if o.respond_to?(:to_hash)
+ h = Hash.new
+ object[0].to_hash.each { |k, v| h[k] = v }
+ return h
+ elsif o.respond_to?(:to_a)
+ h = Hash.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
+ case i.size
+ when 2
+ k = i[0]
+ v = i[1]
+ when 1
+ k = i[0]
+ else
+ raise ArgumentError, "invalid number of elements (#{i.size} for 1..2)"
+ end
+ h[k] = v
end
- h[k] = v
+ return h
end
- return h
end
- raise ArgumentError, 'odd number of arguments for Hash' unless object.length % 2 == 0
+ unless length % 2 == 0
+ raise ArgumentError, 'odd number of arguments for Hash'
+ end
h = Hash.new
- 0.step(object.length - 2, 2) do |i|
+ 0.step(length - 2, 2) do |i|
h[object[i]] = object[i + 1]
end
h