tags:

views:

87

answers:

2

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
Every time I think Ruby is done surprising me, it gets me again. Who woulda thought () is a valid expression?
Wayne Conrad
+1 "nothing much to return"
klochner
+1 Who knew Ruby was so laid back when it comes to evaluating expressions?
Jim Schubert
@klochner, @Jim I guess the ruby authors took the ideas of "lazy evaluation" in a slightly different way :)
Peter
+2  A: 

Playing in irb...

a = ()
a.class # => NilClass
a.nil? # => true
Rob