Step 15: Nil

What happens if we try to access an index that is outside of the array?

my_array = [1, 2, 3, 4, 5]

There is no value at index 17 in my_array, and this is exactly what was returned. In Ruby, nil is an object used to represent the concept of nothing. Variables can be nil, and nil can also be placed in arrays explicitly.

empty_variable = nil
empty_array = [nil, nil, nil]

Another important point with nil is that Ruby treats it as a false value in logical expressions. In Ruby, any object other than nil or false is treated as a true value (this concept is called truthiness).

if 53 && nil

puts(nil == false)

Here we can see that nil and false are not equivalent, but in the if clause the nil does the same thing as false in the case of the logical expression.