method

map

ruby latest stable - Class: Enumerable
map()
public

Returns a new array with the results of running block once for every element in enum.

If no block is given, an enumerator is returned instead.

(1..4).map { |i| i*i }      #=> [1, 4, 9, 16]
(1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]

4Notes

Convert a Hash to an Array of Arrays using map

Alex · Aug 15, 20083 thanks

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:

  • Convert an Array of Arrays to a Hash using Enumerable#inject
  • Convert an Array to a Hash using Hash#[]

Map-like Manipulation of Hash Values

svoop · Oct 30, 20093 thanks

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

stevo · Oct 28, 2010

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"]

Video Explanation for map

MattStopa · Mar 14, 2012