add Enumerable#to_h; ref #2348

parent 17206087
...@@ -669,4 +669,26 @@ module Enumerable ...@@ -669,4 +669,26 @@ module Enumerable
end end
ary ary
end end
##
# call-seq:
# enum.to_h -> hash
#
# Returns the result of interpreting <i>enum</i> as a list of
# <tt>[key, value]</tt> pairs.
#
# %i[hello world].each_with_index.to_h
# # => {:hello => 0, :world => 1}
#
def to_h
h = {}
self.each do |*v|
v = v.__svalue
raise TypeError, "wrong element type #{v.class} (expected Array)" unless v.is_a? Array
raise ArgumentError, "element has wrong array length (expected 2, was #{v.size})" if v.size != 2
h[v[0]] = v[1]
end
h
end
end end
...@@ -144,3 +144,17 @@ assert("Enumerable#zip") do ...@@ -144,3 +144,17 @@ assert("Enumerable#zip") do
assert_equal [[1, 4, 7], [2, 5, 8]], [1, 2].zip(a, b) assert_equal [[1, 4, 7], [2, 5, 8]], [1, 2].zip(a, b)
assert_equal [[4, 1, 8], [5, 2, nil], [6, nil, nil]], a.zip([1, 2], [8]) assert_equal [[4, 1, 8], [5, 2, nil], [6, nil, nil]], a.zip([1, 2], [8])
end end
assert("Enumerable#to_h") do
c = Class.new {
include Enumerable
def each
yield [1,2]
yield [3,4]
end
}
h0 = {1=>2, 3=>4}
h = c.new.to_h
assert_equal Hash, h.class
assert_equal h0, h
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment