How to understand Ruby's .each and .map

后端 未结 5 514
予麋鹿
予麋鹿 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

    The map method takes an enum given some block, and iterates through it doing some logic. In your case the logic is x+1. As you say it will not mutate anything unless you use !.

    each is simply returning the array that is being called.

    Let's take an example of:

    names = ["bob"]
    

    If we do:

    names.each{|names| names + "somestring"}
    

    the output is still ["bob"]. The reason your second example is different is due to the puts.

    As an exercise try doing:

    y = [1,2,3].each {|x| puts x + 1}
    

    You will get:

    2
    3
    4
     [1,2,3]
    

提交回复
热议问题