+ 5
Why can't i directly print nil with puts or print?
This code 2<=>"2" returns nil but when i try to print it with puts or print it does not output anything. Printing numbers does work with puts or print 2<=>1 If i try 'p' or 'pp' with p 2<=>"2" it does print nil. On further testing i came to the conclusion that puts/print can't directly print nil puts nil # no output, in irb shows nil as return value #see last p statement, replace p with puts for demo https://code.sololearn.com/cR3X6x7vy0QY/?ref=app
6 Antworten
+ 8
I precise that i dont know ruby but im curious enough for find the problem... Reading here http://ruby-doc.org/core-2.5.3/Kernel.html#M005961 it seem that p call the .inspect method on the object while print convert object to string and a futher reading of this https://ruby-doc.org/core-2.2.3/NilClass.html explain all
+ 3
Thanks! i get this a little
p nil.inspect # returns string 'nil'
p nil.to_s # returns an empty string ""
p (print nil.inspect, "\n") == (p nil) # returns true(ignoring the 1st two nil)
Now question remains why does ruby simply not display the nil object the way it's written as nil. Instead of returning 'nil', "" a simple nil in both cases would have sufficed.
+ 2
Lord Krishna I think that its a ruby developers decision... If you think about nil, it would represent (if i have understood) nothing and nothing in string is logically an empty string... Futhermore i think that expressions like
print "some string "+nil
will print correctly
"some string " and not "some string nil" that from a purely logic point of view, it would be wrong
+ 2
KrOW True, it's the way the developer designed the language.
Note: while an empty string can represent it, it's not equal to nil.
About your example: By default you can't actually add a string with nil.
print("hi" + nil) # (no implicit conversion of nil into String)
nil + "hi" # (undefined method `+' for nil:NilClass)
+ 1
Lord Krishna Sorry i presumed thats was possible 😅
I seen thats mandatory convert explicitly to string like
print "some string "+ nil.to_s
Anyway, back to pseudo-problem, the important its know the behaviour for dont trap in some stupid bug 😉