Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are all my puts returning =>nil?

Tags:

null

ruby

puts

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

like image 567
Matt Perejda Avatar asked Feb 07 '13 00:02

Matt Perejda


3 Answers

You may want to use p instead of puts.

p prints and then returns the value.

like image 117
Jazz Avatar answered Nov 02 '22 15:11

Jazz


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.

like image 9
Hunter McMillen Avatar answered Nov 02 '22 15:11

Hunter McMillen


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 "
like image 3
Jeffrey Biles Avatar answered Nov 02 '22 15:11

Jeffrey Biles