Why am I getting objects printed twice?

前端 未结 4 1530
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 08:53

When I am in irb or in rails and I create some iteration with each, I am getting the whole struct printed again in my terminal or inside the browser. Example:

相关标签:
4条回答
  • 2020-11-27 09:11

    You see them printed twice: once as side effect, second time as the return value. irb always puts the last return value. The return value for each is its receiver. You cannot avoid that when using irb, but they will not show up when you run the script as standalone software. The First 1, ..., 4 are the outputs of your puts. They are called side effects.

    0 讨论(0)
  • 2020-11-27 09:13

    Because ruby returns in everything even blocks. So your each statement is returning. You're seeing it output because irb shows you the return of everything. In a script it would only output once.

    0 讨论(0)
  • 2020-11-27 09:15

    Run it outside irb, and you shall be enlightened.

    ruby -e `[1,2,3,4].each {|ele| puts ele}`
    
    0 讨论(0)
  • 2020-11-27 09:26

    Every expression in Ruby returns a value; in irb, the value returned by the expression you've just executed is displayed after =>.

    The return value of Enumerable::each is the object that called each - in this case, the array [1,2,3,4]

    0 讨论(0)
提交回复
热议问题