← Back to Ruby Course | Chapter 2: Variables & Types | Lesson 5 of 7

nil

In this page:

  1. nil

nil

nil represents the absence of a value in Ruby, similar to null in other languages, and is an instance of NilClass. Uninitialized instance variables default to nil, and many methods return nil to signal "nothing found". nil.to_s gives an empty string and nil.to_a gives an empty array, which can be convenient in some contexts.

Warning: Calling most methods on nil (other than the ones NilClass itself defines) raises a NoMethodError -- always check for nil before use if it's possible.

Example: nil

markup
value = nil

puts value.nil?
puts value.class
puts value.to_s.empty?

value = "now set"
puts value.nil?
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.