Why am I getting objects printed twice?

女生的网名这么多〃 提交于 2020-02-09 01:56:07

问题


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:

a = [1,2,3,4]

a.each do |number|
  puts n
end

The result in irb terminal or inside the browser:

1
2
3
4

=> [1,2,3,4]

Why does this => [1,2,3,4] appear inside the browser? I can't create a single list in my page because the whole structure appears.


回答1:


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]




回答2:


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.




回答3:


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.




回答4:


Run it outside irb, and you shall be enlightened.

ruby -e `[1,2,3,4].each {|ele| puts ele}`


来源:https://stackoverflow.com/questions/14363330/why-am-i-getting-objects-printed-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!