“puts”语句如何在Ruby中起作用?
我知道,回报总是nil
。
但是知道这个事实我已经开始玩了。 这里是:
>> 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.
现在我将用puts
来做更多的事情,看看它有多强大。
>> 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?
如何puts
nil
值抑制?
好吧,让我们测试一下nil
已经消失的另一种方式。
>> 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?
任何人都可以通过在Ruby的世界中说出puts
的实际行为来帮助我吗?
我将假设的repl, irb
,正在评估您输入的语句并显示最后一个语句的值。
考虑一下:
>> p = puts "hello"; 5 hello => 5 >> p => nil
puts
仍然返回nil
但是repl显示最后一个语句的结果, 5
这与看跌期权没什么关系。
分号分隔多个表达式。 在这种情况下, irb
将仅显示最后一个表达式所评估的内容。
puts
调用to_s
放在它的参数上,这就是为什么puts 1
工作。 puts nil
与puts nil.to_s
相同,这与puts ""
相同(注意IRB输出中的空行)。
其余的只是在等待新输入之前输出最后执行的行的结果。
您的问题不是使用puts
,而是提示对包含多个语句的命令(由分号分隔)执行的操作。
想想这个例子:
irb(main):001:0> "first";"second" => "second"