liveBook · Manning

False

As explained in The Well-Grounded Rubyist, Fourth Edition

false is Ruby's singleton object representing a false Boolean value.

A ticket availability test

A predicate can return false to report that a ticket is unavailable: `def ticket.available?; false; end`. An `if ticket.available?` test then takes its `else` branch. The question mark makes the method call read like a question; it does not itself determine the answer. section 2.2.4

`false` is a Ruby keyword and an object: the sole instance of `FalseClass`. It can be assigned to a variable or passed to a method, but cannot be used as a variable or method name. Comparisons can return it because Ruby methods return objects. section 7.5.2 section 7.5

Distinguish the object `false` from an expression that fails a conditional test. Every expression evaluates to an object, and only `false` and `nil` have a false Boolean value. Thus `0`, `""`, and other objects pass an `if` test. An expression such as `1 == 2` fails because it evaluates to `false`; `puts "hello"` fails as a condition because it returns `nil`. section 2.2.4 section 7.5.2

Table 7.3 Mapping sample expressions to their evaluation results and Boolean values

Expression

Object to which expression evaluates

Boolean value
of expression

1

1

True

0

0

True

1+1

2

True

true

true

True

false

false

False

nil

nil

False

"string"

"string"

True

""

""

True

puts "string"

nil

False

100 > 50

true

True

x = 10

10

True

def x; end

:x

True

class C; end

nil

False

class C; 1; end

1

True

Compare each expression’s resulting object with its Boolean value; they are related, but not interchangeable. section 7.5.2

That distinction matters beyond ordinary method calls. An empty class definition evaluates to `nil` and fails an `if` test, while defining a method can pass the test even when calling that method would return `false`. Boolean arguments are possible too, but a bare `false` argument can obscure what choice it controls. section 7.5.1 section 7.5.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Distinguishes the `FalseClass` singleton from an expression’s Boolean value through evaluated examples and conditional tests.
Examples
Tests ticket availability, zero, strings, comparison results, `puts`, and class and method definitions.
What it assumes
Assumes familiarity with Ruby method calls and conditionals while developing the distinction between Boolean objects and truth values.
What you can do after
Diagnose/debug with it by checking what an expression returns separately from whether its value passes an `if` test.
How it connects
Connects `false` to `nil`, `if` expressions, predicate methods, comparison methods, and `FalseClass`.

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.