Expand All

nil

nil is a special Ruby data type that means "nothing". It's equivalent to null or None in other programming languages.

Goals

  • Know what nil is for

Step 1

How do you set a variable to empty?

Some of the values we could use can be legitimate values, like:

temperature = 0

today_is_friday = false

empty_phrase = ""

Nil to the rescue. Nil means 'nothing'. It's used to show that a variable hasn't been assigned anything yet, or that a function didn't return a value.

Type this in irb:
# Where is the letter "a" in apple?
"apple".index("a")

# Where is the letter "z"?
"apple".index("z")

Step 2

You may have noticed this already:

Type this in irb:
puts "What does puts evalute to?"

Ruby returns what an expression evaluated to. puts puts a string on the screen, but always evaluates to nil.

Step 3

Here's an error message you will see often.

Type this in irb:
     word = "hello"
     word.upcase
     word = nil
     word.upcase
Expected result:
NoMethodError: undefined method 'downcase' for nil:NilClass

What happened?

Type this in irb:
word.class

word was set to nil. Let's look at the alphabetized list of methods the Nil class has.

Type this in irb:
word.methods.sort

The error message told us Nil doesn't have a method called upcase.

Step 4

How can we avoid these errors? There are a few ways to tell if something is nil.

Type this in irb:
word = "something"
word.nil?
word = nil
word.nil?
# Remember, two equals signs asks if something is equal
word == nil

What's going on here?

name = nil
if name.nil?
    puts "The name hasn't been set yet."
else
    puts "Your name is #{name}"
end

Explanation

Further Reading

Next Step: