Ruby nil Value Tutorial

In this section we will learn what the nil value is and how to use it in Ruby.

What is nil Value in Ruby?

The nil value is an object and is Ruby’s way of referring to the absence of a value!

For example, if you create a variable and don’t have the value for it right away, you can pass the value nil which means the variable does not have a value yet!

Also, in case of collection objects like Arrays, Ruby will set the elements of the collection to nil if you just define the length of the array but don’t set any element for it.

Basically, in Ruby, if there’s a variable that is not referring to a value, then the value nil either implicitly (done by Ruby itself) or explicitly will be assigned to the variable.

Example: passing nil value to a variable in Ruby

variable = nil 

if variable
    puts "This is the value of the variable: #{variable}"
    puts "The current value of the variable is nil!"


The current value of the variable is nil!

How does nil object work in Ruby?

Note that the value of the `variable` in the example above is set to `nil`. This means at the moment, the variable is not pointing to any value (object).

So considering the fact that the nil value is considered as a falsy value in Ruby, then if we pass the `variable` as the condition of an if statement, the result will be false and so the body of the if statement will be skipped.

That’s how we got the message in the body of the `else` statement.

Ruby nil? Method

The nil? method is a way of checking if an object or variable contains a nil value or not.

Simply call this method on top of the target object as if this is its instance method, and then you’ll get either the value true or false.

The value true means the object is nil and the value false means otherwise.

Example: using nil? method in Ruby

variable = nil

var2 = "This is a string object"

puts variable.nil?

puts var2.nil?




Top Technologies