Why are all my puts returning =>nil?

泪湿孤枕 提交于 2020-01-02 01:54:13

问题


I know this may seem like a really simple question, but it really bothers me that my puts keep generating "=> nil" and I scoured for an answer but could not find one. Thanks.

puts 'blink ' *4 blink blink blink blink => nil


回答1:


Because that is the return value of puts:

puts(obj, ...) → nil

Writes the given objects to ios as with IO#print. Writes a record separator (typically a newline) after any that do not already end with a newline sequence. If called with an array argument, writes each element on a new line. If called without arguments, outputs a single record separator.

source: http://www.ruby-doc.org/core-1.9.3/IO.html#method-i-puts

Also, I assume this is just in irb? because calling puts doesn't display its return value in normal applications.




回答2:


You may want to use p instead of puts.

p prints and then returns the value.




回答3:


Hunter McMillen's answer is correct.

However, if you want a puts replacement that actually returns a non-nil value, I've created a gem called reputs.

reputs 'blink ' *4
blink blink blink blink
=> "blink blink blink blink "


来源:https://stackoverflow.com/questions/14741329/why-are-all-my-puts-returning-nil

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