Codebase list mruby / 02b2ac8
Merge pull request #2594 from yasuyuki/hash Implement Hash[] Yukihiro "Matz" Matsumoto 9 years ago
2 changed file(s) with 90 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
11
22 # ISO does not define Hash#each_pair, so each_pair is defined in gem.
33 alias each_pair each
4
5 ##
6 # call-seq:
7 # Hash[ key, value, ... ] -> new_hash
8 # Hash[ [ [key, value], ... ] ] -> new_hash
9 # Hash[ object ] -> new_hash
10 #
11 # Creates a new hash populated with the given objects.
12 #
13 # Similar to the literal <code>{ _key_ => _value_, ... }</code>. In the first
14 # form, keys and values occur in pairs, so there must be an even number of
15 # arguments.
16 #
17 # The second and third form take a single argument which is either an array
18 # of key-value pairs or an object convertible to a hash.
19 #
20 # Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200}
21 # Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200}
22 # Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200}
23 #
24
25 def self.[](*object)
26 o = object[0]
27 if o.respond_to?(:to_hash)
28 h = Hash.new
29 object[0].to_hash.each { |k, v| h[k] = v }
30 return h
31 elsif o.respond_to?(:to_a)
32 h = Hash.new
33 o.to_a.each do |i|
34 raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a)
35 k, v = nil
36 case i.size
37 when 2
38 k = i[0]
39 v = i[1]
40 when 1
41 k = i[0]
42 else
43 raise ArgumentError, "invalid number of elements (#{i.size} for 1..2)"
44 end
45 h[k] = v
46 end
47 return h
48 end
49 raise ArgumentError, 'odd number of arguments for Hash' unless object.length % 2 == 0
50 h = Hash.new
51 0.step(object.length - 2, 2) do |i|
52 h[object[i]] = object[i + 1]
53 end
54 h
55 end
456
557 ##
658 # call-seq:
00 ##
11 # Hash(Ext) Test
2
3 assert('Hash.[] Hash') do
4 a = Hash['a_key' => 'a_value']
5
6 assert_equal({'a_key' => 'a_value'}, a)
7 end
8
9 assert('Hash.[] [ [ ["b_key", "b_value" ] ] ]') do
10 a = Hash[ [ ['b_key', 'b_value'] ] ]
11
12 assert_equal({'b_key' => 'b_value'}, a)
13
14 a = Hash[ [ ] ]
15
16 assert_equal({}, a)
17
18 assert_raise(ArgumentError) do
19 Hash[ [ ['b_key', 'b_value', 'b_over'] ] ]
20 end
21
22 assert_raise(ArgumentError) do
23 Hash[ [ [] ] ]
24 end
25 end
26
27 assert('Hash.[] "c_key", "c_value"') do
28 a = Hash['c_key', 'c_value', 'd_key', 1]
29
30 assert_equal({'c_key' => 'c_value', 'd_key' => 1}, a)
31
32 a = Hash[]
33
34 assert_equal({}, a)
35
36 assert_raise(ArgumentError) do
37 Hash['d_key']
38 end
39 end
240
341 assert('Hash#merge!') do
442 a = { 'abc_key' => 'abc_value', 'cba_key' => 'cba_value' }