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:
Syntax
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
value = nil
puts value.nil?
puts value.class
puts value.to_s.empty?
value = "now set"
puts value.nil?
Login to try C/C++/Java/PHP code in the editor
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
- Calling a method on
nil, such asvalue.upcase, which raisesNoMethodError. - Assuming
niland an empty string are the same, whennil.to_sis""butnilis not"". - Testing with
value == nilin ways that miss the safe navigationvalue&.upcase.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: