From 19d3bb2d90f9806ea6cdef97a139de9f2050363a Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Thu, 20 Sep 2018 12:02:35 +0900 Subject: Make `#to_h` to take a block; [ruby-core:89088] --- mrbgems/mruby-array-ext/mrblib/array.rb | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'mrbgems/mruby-array-ext/mrblib') diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index c0995bb99..bb9e61bdd 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -932,4 +932,29 @@ class Array self.map { |row| row[column_index] } end end + + ## + # call-seq: + # ary.to_h -> Hash + # ary.to_h{|item| ... } -> Hash + # + # Returns the result of interpreting aray as an array of + # [key, value] pairs. If a block is given, it should + # return [key, value] pairs to construct a hash. + # + # [[:foo, :bar], [1, 2]].to_h + # # => {:foo => :bar, 1 => 2} + # [1, 2].to_h{|x| [x, x*2]} + # # => {1 => 2, 2 => 4} + # + def to_h(&blk) + h = {} + self.each do |v| + v = blk.call(v) if blk + raise TypeError, "wrong element type #{v.class}" unless Array === v + raise ArgumentError, "wrong array length (expected 2, was #{v.length})" unless v.length == 2 + h[v[0]] = v[1] + end + h + end end -- cgit v1.2.3