How to understand Ruby's .each and .map

后端 未结 5 515
予麋鹿
予麋鹿 2021-01-18 21:00

I am having trouble understanding the differences between map and each, and where and when to use them.

I read \"What does map do?\" and \

5条回答
  •  无人及你
    2021-01-18 21:32

    tl;dr: I use map if I want to change my collection, apply a transformation on it, end up with something different. I use each if I just need to visit every element in a collection.

    Key point is: you should use map if you want to apply a transformation on an array (an enumerable in reality, but let's keep it simple at the beginning). Otherwise, if you don't need to change your array, you can simply use each.

    Note that in the code below you are not mutating the array but you are simply take advantage of the local string to print each string with a suffix.

    names = ['danil', 'edmund']
    names.each { |name| puts name + ' is a programmer' }
    

    Obviously, you could do the same with map but in this case you don't need it and you have to use an each too to print every element. The code would be

    names = ['danil', 'edmund']
    names.map! { |name| name + ' is a programmer' }
    # or names = names.map { |name| name + ' is a programmer' }
    name.each { |name| puts name }
    

提交回复
热议问题