DEV Community

Discussion on: Level Up Your Ruby Skillz: Working With Hashes

Collapse
 
davids89 profile image
David

Thanks, very usefull to perform basic skills. What the difference between each and map? I guess that map has fewer methods or something like that.

Collapse
 
molly profile image
Molly Struve (she/her)

Great question! The difference is in what they return.

When working with hashes each will run a block of code for each key/value pair in your hash and when it is done it will return the original hash

irb:> { a: 1, b: 2}.each{|k, v| v*3 }
=> {:a=>1, :b=>2}

map for a hash(just like an array) will return a new array with the result of executing your block

irb>  { a: 1, b: 2}.map{|k, v| v*3 }
=> [3, 6]

TL;DR

  • If you want to change some element of your hash and return a new array with the changes, use map.
  • If you want to return the original hash use each.