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

Matt Perejda
  • 509
  • 5
  • 14

3 Answers3

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.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • 2
    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 nil – Ismael Abreu Feb 07 '13 at 00:14
  • 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? – Matt Perejda Feb 07 '13 at 19:10
  • 1
    `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. – Hunter McMillen Feb 07 '13 at 20:00
7

You may want to use p instead of puts.

p prints and then returns the value.

eebbesen
  • 5,070
  • 8
  • 48
  • 70
Pilo
  • 1,210
  • 15
  • 11
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 "
Jeffrey Biles
  • 988
  • 7
  • 24