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

nil

nil is Ruby's way of saying 'nothing here', like an empty box. It is different from zero, which is a number, because nil means there is no value at all.

In this page:

  1. nil
Syntax
ruby
variable = nil
variable.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?
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling a method on nil, such as value.upcase, which raises NoMethodError.
  2. Assuming nil and an empty string are the same, when nil.to_s is "" but nil is not "".
  3. Testing with value == nil in ways that miss the safe navigation value&.upcase.
🔒

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.