liveBook · Manning

Missing value

As explained in The Well-Grounded Rubyist, Fourth Edition

nil is Ruby’s singleton object representing the absence of a meaningful value.

Ruby uses `nil` to represent the absence of a meaningful value. It is still an object—the sole instance of `NilClass`—and it responds to methods. For example, `nil.to_s` returns an empty string and `nil.to_i` returns `0`; neither conversion makes `nil` an empty string or a number. section 7.5.3

An expression’s result and its truth value are different questions. `nil` and `false` are the only objects that fail an `if` test. Zero, an empty string, and empty collections pass it. Thus `nil` can signal a negative test outcome without being the same object as `false`. section 7.5.2 section 7.5.3

Several ordinary operations produce `nil`:

  • `puts "Hello"` prints the string but returns `nil`. In irb, the printed string and the displayed `=> nil` are two different outputs. section 1.4.2
  • An `if` expression with a failed condition and no `else` evaluates to `nil`. section 2.2.4
  • An uninitialized instance variable or an out-of-range array element yields `nil`. Reading an undefined local variable instead raises an error. section 7.5.3

Absence matters when calling methods. If `roster.players` is `nil`, `roster.players.first` raises `NoMethodError`. Safe navigation calls the next method only when its receiver is not `nil`: `roster.players&.first&.position` yields `nil` instead of raising when a link is missing. section 6.4.4

Seeing an unassigned value during debugging

At a breakpoint before a temperature conversion, `rdbg` displays `celsius = nil`. After stepping past its assignment, inspecting `celsius` displays `100`. The two inspections distinguish a value not yet assigned at that point from the value later used in the calculation. section 1.4.5

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines nil as NilClass’s sole instance, works through truth values and common returns, then shows how safe navigation handles nil receivers.
Examples
Uses irb results for puts and array indexing, plus a roster method chain and debugger inspection of an unassigned value.
What it assumes
Assumes familiarity with Ruby expressions, method calls, and conditionals while defining nil’s object identity and truth value.
What you can do after
Diagnose/debug with it by recognizing nil results and avoiding NoMethodError on nil receivers with `&.`.
How it connects
Connects nil to truthiness, conditional expressions, return values, instance variables, arrays, NoMethodError, and safe navigation.

Also explained in

Compare how 35 books explain missing value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.