Why are all my puts returning =>nil?
Asked Answered
R

3

9

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

Ragin answered 7/2, 2013 at 0:7 Comment(0)
R
9

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.

Reedbuck answered 7/2, 2013 at 0:8 Comment(3)
I would add that every instruction in ruby returns something. Every method, attribution, declaration (of classes, methods). And in irb that's what you see, the returned value (or evaluation). So the methods that dosen't make sense to return anything they just return nilAcclimatize
Thank you. This is very helpful to me. You are correct, I am using irb. I get the sense that I would be better off programming in a normal application. I am novice, do you think you could elaborate?Ragin
irb is fine to program in, I was just making a point that in any ruby program outside of irb unless you specifically check the return value, it won't display it to you.Reedbuck
D
7

You may want to use p instead of puts.

p prints and then returns the value.

Dim answered 9/2, 2015 at 19:11 Comment(0)
W
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 "
Weaken answered 2/2, 2014 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.