mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
add Enumerable#to_h; ref #2348
This commit is contained in:
@@ -669,4 +669,26 @@ module Enumerable
|
||||
end
|
||||
ary
|
||||
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
|
||||
|
||||
@@ -144,3 +144,17 @@ assert("Enumerable#zip") do
|
||||
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])
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user