One use of nil
you often see in Ruby code is the following:
a ||= 10 # or a = a || 10
This works because once a variable has been seen on the left hand side of an assignment, it implicitly has the value nil.
>> if false
.. x = y
.. z
.. end
=> nil
>> x
=> nil
>> z
NameError: undefined local variable or method `z' for main:Object
Thus when the a || 10
part is evaluated, it evaluates to nil || 10
, which yields 10.
nil
and false
are also the only two values in Ruby that are logically false, so it's customary for methods to return nil
in case of failure. There's a gem called andand
that makes use of exactly this, so instead of something like
@first_name &&= @first_name.trim
you can write
@first_name.andand.trim
This basically translates to trim @first_name
if it has a value other than nil
, otherwise evaluate to nil
. As you can imagine this is particularly useful when chaining methods where one of the intermediaries can potentially return nil
.
Besides that nil
is also returned when you are trying to access non-existing collection elements, e.g. in the case of arrays or hashes. Uninitialized instance variables also have the value nil
.
I'm not overly versed in Python, but from what I've seen nil
and None
serve pretty much the same purpose.