Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Why does nil.to_s return "", but nil.inspect returns "nil"

Tags:

null

ruby

Why does nil.to_s return "", but nil.inspect returns "nil" (when apparently .inspect uses the .to_s method)

like image 761
micklec Avatar asked Sep 12 '12 19:09

micklec


1 Answers

The "inspect" method of the Object class is supposed to return a human-readable version of the object.

The human-readable version of nil is "nil" and not "" (which is the human readable version of the string "").
That's why nil.inspect should return "nil", whereas nil.to_s returns "" in order for "a string" + nil to return "a string" as it is generally expected (in other languages for instance).

like image 80
dureuill Avatar answered Sep 22 '22 01:09

dureuill