I’ve spent a lot of time working on increasing my knowledge of Ruby on Rails recently, and I had someone explain to me the three different ways to iterate through maps in Ruby. I was super excited about this because up until this point I thought there was only one way to iterate through maps, and once I saw these other forms, I realized I’ve actually seen them before.
Let’s say I had a list of elements in an Array like this: cafe = ["latte", "drip_coffee", "cappucchino", "tea"]
and I wanted to get the first letter of each element. The most explicit way I could write this out would be to put it in a do-block like this:
cafe.map do |c|
c.first
end
Another way would be to condense the statement like this:
cafe.map { |c| c.first }
And an even more abbreviated way to do this would be to do:
cafe.map(&:first)
I’ve definitely seen the last one in code before, and I’ve been really confused about what it’s doing, but now I know it’s basically taking the element from the map and applying the method in parentheses to it.