How come ().nil? is true in Ruby?
+8
A:
Simple answer: ()
is an empty expression that evaluates to nil
.
More detailed: all expressions have a result in Ruby, returning nil
if there's nothing better to return. ()
doesn't cause any action by itself, so an expression that is merely ()
has nothing in particular to return. Thus the result of the expression is set to nil
, and so ().nil?
evaluates an empty expression, decides there's nothing much to return so returns nil
. This is indeed equal to nil
, so nil?
says true
.
Peter
2010-01-27 23:43:19
Every time I think Ruby is done surprising me, it gets me again. Who woulda thought () is a valid expression?
Wayne Conrad
2010-01-28 00:41:23
+1 "nothing much to return"
klochner
2010-01-28 00:52:31
+1 Who knew Ruby was so laid back when it comes to evaluating expressions?
Jim Schubert
2010-01-28 00:56:47
@klochner, @Jim I guess the ruby authors took the ideas of "lazy evaluation" in a slightly different way :)
Peter
2010-01-28 01:14:25