Nothingness and the Truth
An introduction to Nil, True and False objects.
Now is a good time to talk about the concepts of nothingness and truth in Ruby.
Nil
We have briefly mentioned that in Ruby there is an object that represents
"nothing": the object nil
.
That’s right. “Nothing” is a thing in Ruby (as well as in many other languages), albeit a very special one. We could ramble on the philosophical implications of this, but instead we’ll just look at how this is used in practice:
Remember how we can receive a value associated with a key from a hash?
dictionary = { :one => "eins", :two => "zwei", :three => "drei" }p dictionary[:one]
This will print out "eins"
. However, what happens if we try to receive
the value for a key that has not been defined on the hash?
dictionary = { :one => "eins", :two => "zwei", :three => "drei" }p dictionary[:four]
This will print out nil
. Remember that every method call always will return
some value? In cases where there’s nothing to return, it will return nil
,
which represents nothing :)
In Ruby, nil
, nothing, is something else than, for example, 0
, which
represents something. An empty string ""
, an empty array []
, or empty
Hash {}
also all represent something. So they’re not nil
. ...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy