RCR: Array#to_h

S

Steven Lumos

Marcel Molina Jr. said:
Abstract

A simple method that construct a hash from an array. Just like Hash#to_a
return an array from hash.

Having your proposed to_h accept a block is a nice idea but as it is you can
do the non-block version quite easily:
Hash[*%w(a b c d)] => {"a"=>"b", "c"=>"d"}
keys = %w(a b c d) => ["a", "b", "c", "d"]
values = [1, 2, 3, 4] => [1, 2, 3, 4]
Hash[*keys.zip(values).flatten]
=> {"a"=>1, "b"=>2, "c"=>3, "d"=>4}

And the block version:
a = [1,2,3,4,5] => [1, 2, 3, 4, 5]
Hash[*a.map {|e| [e, 2*e]}.flatten]
=> {5=>10, 1=>2, 2=>4, 3=>6, 4=>8}

Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top