summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorINOUE Yasuyuki <[email protected]>2014-09-06 22:50:06 +0900
committerINOUE Yasuyuki <[email protected]>2014-09-06 22:50:06 +0900
commit5603b8d79f3726466fdab60905c16439b59c6c3e (patch)
treea7698efc88e147e0ef5cdbd17306ce4031ef9b42
parentcc98f191fad94409fa4a6edef0c788fb45c82587 (diff)
downloadmruby-5603b8d79f3726466fdab60905c16439b59c6c3e.tar.gz
mruby-5603b8d79f3726466fdab60905c16439b59c6c3e.zip
implement Hash.[]
-rw-r--r--mrbgems/mruby-hash-ext/mrblib/hash.rb33
-rw-r--r--mrbgems/mruby-hash-ext/test/hash.rb38
2 files changed, 71 insertions, 0 deletions
diff --git a/mrbgems/mruby-hash-ext/mrblib/hash.rb b/mrbgems/mruby-hash-ext/mrblib/hash.rb
index 9da08dc3a..6546af644 100644
--- a/mrbgems/mruby-hash-ext/mrblib/hash.rb
+++ b/mrbgems/mruby-hash-ext/mrblib/hash.rb
@@ -3,6 +3,39 @@ class Hash
# ISO does not define Hash#each_pair, so each_pair is defined in gem.
alias each_pair each
+ 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} at #{__LINE__} (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
+ return h
+ end
+ raise ArgumentError, 'odd number of arguments for Hash' unless object.length % 2 == 0
+ h = Hash.new
+ t = (0...(object.length >> 1)).map { |i| i * 2 }
+ for i in t do
+ h[object[i]] = object[i + 1]
+ end
+ h
+ end
+
##
# call-seq:
# hsh.merge!(other_hash) -> hsh
diff --git a/mrbgems/mruby-hash-ext/test/hash.rb b/mrbgems/mruby-hash-ext/test/hash.rb
index 2bc5b911a..e1afdaaa3 100644
--- a/mrbgems/mruby-hash-ext/test/hash.rb
+++ b/mrbgems/mruby-hash-ext/test/hash.rb
@@ -1,6 +1,44 @@
##
# Hash(Ext) Test
+assert('Hash.[] Hash') do
+ a = Hash['a_key' => 'a_value']
+
+ assert_equal({'a_key' => 'a_value'}, a)
+end
+
+assert('Hash.[] [ [ ["b_key", "b_value" ] ] ]') do
+ a = Hash[ [ ['b_key', 'b_value'] ] ]
+
+ assert_equal({'b_key' => 'b_value'}, a)
+
+ a = Hash[ [ ] ]
+
+ assert_equal({}, a)
+
+ assert_raise(ArgumentError) do
+ Hash[ [ ['b_key', 'b_value', 'b_over'] ] ]
+ end
+
+ assert_raise(ArgumentError) do
+ Hash[ [ [] ] ]
+ end
+end
+
+assert('Hash.[] "c_key", "c_value"') do
+ a = Hash['c_key', 'c_value', 'd_key', 1]
+
+ assert_equal({'c_key' => 'c_value', 'd_key' => 1}, a)
+
+ a = Hash[]
+
+ assert_equal({}, a)
+
+ assert_raise(ArgumentError) do
+ Hash['d_key']
+ end
+end
+
assert('Hash#merge!') do
a = { 'abc_key' => 'abc_value', 'cba_key' => 'cba_value' }
b = { 'cba_key' => 'XXX', 'xyz_key' => 'xyz_value' }