summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-array-ext/mrblib/array.rb
diff options
context:
space:
mode:
authorYukihiro "Matz" Matsumoto <[email protected]>2018-09-20 12:02:35 +0900
committerYukihiro "Matz" Matsumoto <[email protected]>2018-09-20 13:47:29 +0900
commit19d3bb2d90f9806ea6cdef97a139de9f2050363a (patch)
tree65b6de226502d8fb5ba02fca8708f3b2ec1a02a1 /mrbgems/mruby-array-ext/mrblib/array.rb
parentfa5f5954daa95b6e03bcbe16ffcce4d5e1946146 (diff)
downloadmruby-19d3bb2d90f9806ea6cdef97a139de9f2050363a.tar.gz
mruby-19d3bb2d90f9806ea6cdef97a139de9f2050363a.zip
Make `#to_h` to take a block; [ruby-core:89088]
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
-rw-r--r--mrbgems/mruby-array-ext/mrblib/array.rb25
1 files changed, 25 insertions, 0 deletions
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 <i>aray</i> as an array of
+ # <tt>[key, value]</tt> pairs. If a block is given, it should
+ # return <tt>[key, value]</tt> 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