How “puts” statement works in Ruby?

夙愿已清 提交于 2020-01-25 23:19:35

问题


I knew that puts return always nil by itself.

But knowing that fact already I have started to play around it. here it is:

>> puts

=> nil # Good, you are doing what I expected.

>> puts 15
15
=> nil # nil is for puts and 15 it printed,as it is assigned to do. perfect still.

>> puts a = 5 + 2
7
=> nil # still good.

Now I will do a bit more with puts to see how robust it is.

>> puts a= 5 + 2;b= 2+3
7
=> 5 #ahh! where is nil?

>> puts a= 5 + 2;b= 2+3;c= 4+8
7
=> 12 # again no nil. Another confusion created here that why 12 and 7 only, how 5 has been skipped?

How puts nil value has been suppressed ?

Okay, so lets test another way where nil has been gone.

>> x=puts a= 5 + 2;b= 2+3;c= 4+8
7
=> 12

>> puts x

=> nil # humm, nil is there. but why not nil => nil? Confusion here again goes up. whose nil is it?

Can anyone help me by saying the actual behaviour of puts in Ruby's world?


回答1:


The repl, irb I will assume, is evaluating the statement(s) you enter and displaying the value of the last statement evaluated.

Consider this:

>> p = puts "hello"; 5
hello
 => 5 
>> p
 => nil 

puts is still returning nil but the repl is displaying the result of the last statement, 5




回答2:


This doesn't have much to do with puts.

A semicolon separates multiple expressions. irb will in this case only display what the last expression evaluated to.




回答3:


putscalls to_s on it's argument, that's why puts 1 works. puts nil is the same as puts nil.to_s, and that is the same as puts "" (note the blank line in the IRB output).

The rest is just irb outputting the result of the last executed line, before waiting on new input.




回答4:


Your problem isn't with puts, but what the prompt does with commands containing multiple statements (separated by semi-colons).

Think on this example:

irb(main):001:0> "first";"second"
=> "second"


来源:https://stackoverflow.com/questions/14899116/how-puts-statement-works-in-ruby

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