nil

suggest change

nil is Ruby's "no value". A method returns it when it has nothing to give back, a variable holds it before you assign anything useful, and a hash returns it for a key that isn't there.

Unlike null in Java or C#, nil is a real object. It has a class, it responds to methods and you can pass it around like any other value:

p nil.class      # => NilClass
p nil.nil?       # => true
p nil.to_s       # => ""
p nil.inspect    # => "nil"
p nil.frozen?    # => true

This article covers where nil comes from, how it behaves in conditions, how to convert it, and the idioms Ruby gives you for handling it safely.

nil is a singleton

There's exactly one nil object in a Ruby process. NilClass can't be instantiated, and copying nil gives you nil back:

begin
  NilClass.new
rescue NoMethodError => e
  p e.message # => "undefined method 'new' for class NilClass"
end

p nil.dup.equal?(nil) # => true
p nil.object_id       # => 4 (fixed in CRuby)
p NilClass.ancestors  # => [NilClass, Object, Kernel, BasicObject]

Because NilClass inherits from Object, nil has all the usual methods (inspect, then, instance_of?, frozen? and so on). NilClass itself defines a small set:

p NilClass.instance_methods(false).sort
# => [:&, :===, :=~, :^, :inspect, :nil?, :rationalize,
#     :to_a, :to_c, :to_f, :to_h, :to_i, :to_r, :to_s, :|]

Where nil comes from

You rarely write nil yourself. Most of the time it comes back from a method that had nothing to return.

A method or block whose last expression is empty, or an if without a matching branch, evaluates to nil:

def nothing; end
p nothing                # => nil

p(if false then 1 end)   # => nil

text = "x" if false
p text                   # => nil  (the variable exists, but is nil)

puts and print return nil. That's why irb shows => nil after every puts:

result = puts("hi")      # prints: hi
p result                 # => nil

Lookups that find nothing return nil instead of raising:

h = {a: 1}
a = [1, 2, 3]

p h[:b]                   # => nil
p a[10]                   # => nil
p [].first                # => nil
p [].max                  # => nil
p a.find { _1 > 5 }       # => nil
p "hello".index("z")      # => nil
p "hello" =~ /z/          # => nil
p "hello"[/z/]            # => nil
p ENV["NO_SUCH_VAR_XYZ"]  # => nil

Uninitialized instance variables are nil too:

p @foo # => nil

nil is falsy

In a condition, only nil and false count as false. Everything else is true, including 0, "" and []. See Truthy and Falsy values for the full rules.

[nil, false, 0, "", []].each do |v|
  puts "#{v.inspect.ljust(5)} -> #{v ? "truthy" : "falsy"}"
end

Output:

nil   -> falsy
false -> falsy
0     -> truthy
""    -> truthy
[]    -> truthy

nil and false are both falsy but they're not equal:

p nil == false  # => false
p !!nil         # => false

if x versus x.nil?

if x and unless x.nil? are not the same test. When false is a valid value, use nil?:

val = false

p(val ? "truthy" : "falsy")       # => "falsy"
p(val.nil? ? "nil" : "not nil")   # => "not nil"

This matters for flags and settings. If enabled can be true, false or "not set", only nil? tells "not set" apart from false.

nil? is defined on every object. It returns true only for nil:

p nil.nil?    # => true
p 0.nil?      # => false
p false.nil?  # => false
p "".nil?     # => false

Prefer x.nil? over x == nil. Both work, but nil? can't be fooled by a class that overrides ==.

NoMethodError on nil

The most common error in Ruby programs is calling a method on a value you expected to be something else, but which turned out to be nil:

user_name = {id: 1}[:name]

begin
  user_name.upcase
rescue NoMethodError => e
  p e.message   # => "undefined method 'upcase' for nil"
  p e.receiver  # => nil
  p e.name      # => :upcase
end

The error is raised where nil is used, which is often far from where it was produced. The fixes below are about either providing a default, skipping the call, or failing early with a clearer error.

Providing a default with ||

x || default returns x if it's truthy, otherwise default. It's the shortest way to replace nil:

name = nil
puts "Hello, #{name || "stranger"}!"   # Hello, stranger!

||= assigns only if the variable is currently nil or false. It's commonly used for memoization; see Or-equals (||=) conditional assignment:

y = nil
y ||= 5
p y # => 5

class Report
  def data
    @data ||= expensive_load
  end

  private

  def expensive_load
    puts "loading..."
    [1, 2, 3]
  end
end

r = Report.new
r.data # prints "loading..." once
r.data # cached

Both || and ||= also replace false. If false is a legitimate value you want to keep, test with nil? instead:

z = false
z ||= 5
p z # => 5, probably not what you wanted

z = false
z = 5 if z.nil?
p z # => false

A memoized method that can legitimately return nil or false will recompute every time with ||=. Use defined? or instance_variable_defined? for that case:

def lookup
  return @lookup if defined?(@lookup)
  @lookup = nil # expensive computation that may return nil
end

Skipping calls with &.

The safe navigation operator &. calls a method only when the receiver isn't nil. If it is nil, the whole expression returns nil:

s = nil
p s&.length         # => nil
p s&.length || 0    # => 0

p "abc".match(/b/)&.[](0)  # => "b"
p "abc".match(/z/)&.[](0)  # => nil

It also works for attribute assignment. The assignment is skipped when the receiver is nil:

Person = Struct.new(:name)

person = Person.new(nil)
person&.name = "Ann"
p person.name # => "Ann"

nobody = nil
nobody&.name = "Ann" # does nothing
p nobody             # => nil

&. only checks for nil. Calling false&.length still raises NoMethodError.

Long &. chains (a&.b&.c&.d) are often a sign that a value is optional in too many places. Consider handling nil once, at the boundary where it enters your code.

Digging into nested data

Hash#dig and Array#dig walk a nested structure and return nil as soon as a step is missing, instead of raising:

data = {user: {address: {city: "Paris"}}}

p data.dig(:user, :address, :city)   # => "Paris"
p data.dig(:user, :phone, :number)   # => nil

# without dig, this raises NoMethodError on nil:
# data[:user][:phone][:number]

Hash lookups: [] versus fetch

hash[key] returns nil both when the key is missing and when the key maps to nil. Use key? to tell them apart:

h = {a: nil}

p h[:a]        # => nil
p h[:b]        # => nil
p h.key?(:a)   # => true
p h.key?(:b)   # => false

fetch raises KeyError for a missing key, which makes typos and missing configuration fail loudly. It also takes a default:

h = {a: 1}

begin
  h.fetch(:b)
rescue KeyError => e
  p e.message      # => "key not found: :b"
end

p h.fetch(:b, 0)   # => 0
p h.fetch(:b) { |k| "no #{k}" } # => "no b"

Note the difference when the key exists but holds nil. fetch only uses the default for a missing key:

config = {timeout: nil}

p config.fetch(:timeout, 30)  # => nil  (key exists)
p config[:timeout] || 30      # => 30
p config.fetch(:retries, 3)   # => 3

A hash created with a default value returns that default instead of nil:

counts = Hash.new(0)
p counts[:missing] # => 0

Converting nil

nil converts to the "empty" value of each basic type:

p nil.to_s   # => ""
p nil.to_a   # => []
p nil.to_h   # => {}
p nil.to_i   # => 0
p nil.to_f   # => 0.0
p nil.to_r   # => (0/1)
p nil.to_c   # => (0+0i)

String interpolation calls to_s, so nil disappears silently:

name = nil
puts "[#{name}]"   # []
p "Name: #{name}"  # => "Name: "

This is convenient but can hide bugs; an empty field in a generated report is often a nil that shouldn't be there.

The conversion functions in Kernel behave differently. Array() and String() accept nil, but Integer() and Float() refuse it:

p Array(nil)     # => []
p Array([1])     # => [1]
p Array(1..3)    # => [1, 2, 3]
p String(nil)    # => ""

begin
  Integer(nil)
rescue TypeError => e
  p e.message    # => "can't convert nil into Integer"
end

p Integer(nil, exception: false) # => nil

Array(x) is a handy way to accept "nothing, one thing or a list" without checking:

def notify(recipients)
  Array(recipients).each { |r| puts "notify #{r}" }
end

notify(nil)              # prints nothing
notify("ann")            # notify ann
notify(["bob", "cid"])   # notify bob, notify cid

nil in collections

Removing nils

compact removes nil elements from an array, and nil values from a hash. See Remove all nil elements from an array with compact:

p [1, nil, 2, nil].compact   # => [1, 2]
p({a: nil, b: 1}.compact)    # => {b: 1}

filter_map maps and drops nil (and false) results in one pass:

p ["1", "x", "3"].filter_map { Integer(_1, exception: false) }
# => [1, 3]

Sorting and summing

nil isn't comparable with other values, so sorting or summing an array that contains it raises:

begin
  [3, nil, 1].sort
rescue ArgumentError => e
  p e.message # => "comparison of NilClass with 3 failed"
end

begin
  [1, nil].sum
rescue TypeError => e
  p e.message # => "nil can't be coerced into Integer"
end

Either compact first, or decide where nil should go. This puts nil last:

p [3, nil, 1].sort_by { _1 || Float::INFINITY } # => [1, 3, nil]

Searching for nil

nil works with the case-equality methods, so grep, count and the predicate methods all understand it:

values = [1, nil, "a", nil]

p values.count(nil)     # => 2
p values.grep(NilClass) # => [nil, nil]
p values.grep_v(nil)    # => [1, "a"]
p [nil, nil].all?(nil)  # => true
p [nil, false].any?     # => false (both falsy)

nil in case and pattern matching

nil matches itself in when and in clauses:

def describe(x)
  case x
  when nil     then "nothing"
  when Integer then "number #{x}"
  else              "something else"
  end
end

p describe(nil)  # => "nothing"
p describe(5)    # => "number 5"

case [1, nil]
in [Integer => n, nil]
  puts "second element missing, first is #{n}"
end
# second element missing, first is 1

nil as a default argument

nil is the usual default for an optional argument. The downside is that the method can't tell "not passed" from "passed nil". If that difference matters, use a private sentinel object:

NOT_GIVEN = Object.new

def greet(name = NOT_GIVEN)
  return "no argument" if name.equal?(NOT_GIVEN)
  return "explicit nil" if name.nil?
  "hello #{name}"
end

p greet          # => "no argument"
p greet(nil)     # => "explicit nil"
p greet("bob")   # => "hello bob"

**nil in a method definition declares that the method accepts no keyword arguments at all. At a call site, **nil splats nothing (Ruby 3.4+), which is handy when an options hash may be nil:

def no_kwargs(**nil) = :ok

p no_kwargs # => :ok

begin
  no_kwargs(x: 1)
rescue ArgumentError => e
  p e.message # => "no keywords accepted"
end

def with_kwargs(**kw) = kw
opts = nil
p with_kwargs(**opts) # => {}

Returning nil versus raising

Returning nil is a good signal for "not found" when not finding something is normal, such as find, index or a hash lookup. The caller decides what to do:

def safe_div(a, b) = b.zero? ? nil : a / b

result = safe_div(4, 0) or puts "division failed"
# division failed

When a missing value means something is wrong, raise instead. A nil returned from deep inside your code turns into a NoMethodError somewhere else, and the stack trace points at the wrong place. Ruby's own APIs follow this split: find returns nil, but fetch raises; Integer("x") raises, but Integer("x", exception: false) returns nil.

Predicate methods (ending in ?) should return true or false, not nil. Use !! or an explicit comparison if the underlying value might be nil:

class Account
  def initialize(email) = @email = email
  def email? = !@email.nil?
end

p Account.new(nil).email?        # => false
p Account.new("a@b.com").email?  # => true

The Null Object pattern

Instead of checking for nil everywhere, you can return an object that responds to the same methods with harmless defaults. This is the Null Object pattern:

class GuestUser
  def name = "Guest"
  def admin? = false
  def orders = []
end

User = Struct.new(:name, :orders) do
  def admin? = name == "root"
end

USERS = {1 => User.new("alice", [10, 20])}

def current_user(id)
  USERS[id] || GuestUser.new
end

[1, 99].each do |id|
  u = current_user(id)
  puts "#{u.name}: admin=#{u.admin?}, orders=#{u.orders.size}"
end

Output:

alice: admin=false, orders=2
Guest: admin=false, orders=0

The code that uses current_user never sees nil, so it doesn't need &. or if checks.

blank? and present? are not core Ruby

Rails code uses blank? and present?, which treat nil, false, "", whitespace-only strings and empty collections as "blank". These come from ActiveSupport, not from Ruby. In plain Ruby, combine nil handling with an emptiness check yourself:

def blank?(s) = s.nil? || s.strip.empty?

p blank?(nil)   # => true
p blank?("  ")  # => true
p blank?("hi")  # => false

v = nil
p v.to_s.empty? # => true, shorter when v is a String or nil

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents