Nothingness and the Truth
Learn about truthiness, falsiness, and nothingness.
Now is a good time to explore the concepts of nothingness and truth in Ruby. First, let’s also do a quick recap to build some context.
The nil
object
We’ve briefly mentioned that in Ruby, there’s an object that represents nothing, nil
.
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 prints out "eins"
. However, what happens if we try to receive the value for a key that hasn’t been defined on the hash?
dictionary = { :one => "eins", :two => "zwei", :three => "drei" }p dictionary[:four]
This prints out nil
. Remember that every method call always returns some value. In cases where there’s nothing to return, it returns nil
, which represents nothing.
Note that nil
isn’t 0
, which represents something. An empty string (""
), an empty array ([]
), or an empty hash ({}
) also all represent something. So, they’re not nil
. ...