1 | 1 |
|
2 | 2 |
# ISO does not define Hash#each_pair, so each_pair is defined in gem.
|
3 | 3 |
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
|
4 | 56 |
|
5 | 57 |
##
|
6 | 58 |
# call-seq:
|