Why puts and print return nil in ruby?
nil
is the Ruby object, not just a keyword, that represents nothingness. Whenever a method doesn’t return a useful value, it returns nil.
The nil object is the only instance of a special Ruby class – the NilClass
. Many expressions can have a false value, but the only two object to have a boolean value of false are nil
and false
. puts
and print
are methods that return nil:
[55] pry(main)> print something Hey! Ruby is awesome=> nil [56] pry(main)> puts something Hey! Ruby is awesome => nil [57] pry(main)> p something "Hey! Ruby is awesome" => "Hey! Ruby is awesome"
How do the puts and print methods actually output text to your console?
They use the $stdout
global variable provided to us by Ruby. (You don’t need to worry about writing global variables right now.) For the purposes of understanding how puts and print work, we just need to understand the following:
Ruby uses the $stdout
global variable to communicate with your computers standard output stream (this happens through various other intermediaries which we won’t delve into now). So in a basic sense, puts and print actually use the $stdout
variable to send the information to the output stream on your computer which communicates with your operating system and outputs that information to the console.
You can absolutely employ puts and print without understanding everything that was just described. But if you do understand it, then you now have a basic sense of what is happening under the hood of these methods.
Always remember the golden rule
of method in ruby, that a method would return it’s last line
. To prevent the nil as the output of print, you can print a line break after it, and optionally put some other value as the last statement of your code, then the Console will show it instead of nil:
print "hey, Ruby is awesome!" puts "\n" true
produces:
hey, Ruby is awesome! true
How is p
different from puts and print?
It is similar to puts in that it adds a newline, but rather than calling to_s
, p
calls inspect
. And also doesn't
return nil
.
[57] pry(main)> p something "Hey! Ruby is awesome" => "Hey! Ruby is awesome"
Bonus Info :
Just like with true and false, every nil you use in your Ruby application will be the same instance as you will find out if you query it’s id. The id of the nil object is 8. Don’t ask me why, I have no idea 🙂
irb(main):001:0> nil.class => NilClass irb(main):002:0> nil.object_id => 8 irb(main):002:0> nil.to_s => "" irb(main):003:0> nil.to_i => 0
The value of the object_id of nil changed in ruby 2; it is now 8. (True and False got renumbered too)
Relevant section in the ruby source where this value is defined is https://github.com/ruby/ruby/blob/v2_0_0_0/include/ruby/ruby.h#L383-431
The change is related to Flonums, and the discussion prior to this change is viewable at https://bugs.ruby-lang.org/issues/6763
oh okay. Thank you so much Matt 🙂 . Have updated it in the post.