map
map()
public
Convert a Hash to an Array of Arrays using map
Although you’ll always have to_a and it’s faster, this trick is too cool to ignore…
When the block is omitted, collect or map uses this implied block: {|item| item}, which means when applied on an hash without a block, collect/map returns an array containing a set of two-item arrays, one for each key/value pair in the hash. For each two-item array, item 0 is the key and item 1 is the corresponding value.
burgers = {"Big Mac" => 300, "Whopper with cheese" => 450, "Wendy's Double with cheese" => 320} burgers.map => [["Wendy's Double with cheese", 320], ["Big Mac", 300], ["Whopper with cheese", 450]]
see also:
Map-like Manipulation of Hash Values
Let’s say you want to multiply all values of the following hash by 2:
hash = { :a => 1, :b => 2, :c => 3 }
You can’t use map to do so:
hash.map {|k, v| v*2 } # => [6, 2, 4]
However, with merge you can:
hash.merge(hash) {|k,v| v*2 } => {:c=>6, :a=>2, :b=>4}
(The above is Ruby 1.8, in Ruby 1.9 the order is preserved.)
map_with_index
Of course such a method does not exist, however we can simulate it easily
%w(a b c).to_enum(:each_with_index).map{|a,i| "#{a}, #{i}"} => ["a, 0", "b, 1", "c, 2"]