any?, all?, none? without a block

Free preview 3 min to read

What the select course already covered

The lesson "Related Enumerable methods", in the intern course Ruby enumerable: select, showed any?, all? and none? running with a block: numbers.any? { |n| n > 4 }, numbers.all? { |n| n > 0 }, numbers.none? { |n| n > 10 }. It also covered count and find. None of that is repeated here. This course starts from a question that lesson never asked: what happens with no block at all?

Every element judged by its own truthiness

[1, 2, 3].all?
# true, every element is truthy

[1, nil, 3].any?
# true, at least one element (1) is truthy

[nil, false].any?
# false, neither element is truthy

Without a block, any?, all? and none? don't compare elements with anything. They ask whether each element, as it is, counts as truthy or falsy in Ruby's sense. Only nil and false are falsy; everything else, including 0 and "", is truthy.

A mix that matters

[1, false, 3].all?
# false, false itself breaks "every element is truthy"

[1, 2, 3].any?
# true, obviously, but so is a single [0]:
[0].any?
# true, 0 is truthy in Ruby, unlike some other languages

The last line deserves a second look. Someone coming from a language where 0 is falsy would expect [0].any? to be false. In this app's Ruby 4.0.1 it's true. 0 is a valid Ruby object that is neither nil nor false, and any? with no block only asks "is this nil or false?"

When the no-block form shows up

Code that checks something specific usually uses the block form, all? { |x| x.valid? }. The no-block form is useful when a collection already holds the booleans you're asking about:

checks = [user.present?, user.active?, user.email.present?]
checks.all?
# true only if every individual check already came back truthy

Building an array of conditions first and then asking all? (or any?) about the whole batch reads cleanly, and you don't repeat the three checks inside a block. (present? comes from Rails' Active Support; the pattern works with any booleans.)

Key takeaways

  • Without a block, any?, all? and none? check each element's own truthiness, with no comparison or outside condition.
  • Only nil and false are falsy in Ruby; 0, "" and every other object, empty arrays and hashes included, are truthy.
  • [0].any? is true, a gotcha for anyone who expects 0 to be falsy as in some other languages.
  • The no-block form fits once a collection already holds a batch of booleans to check at once.
Lesson 1 of 7 · free

Keep going with lesson 2

The pattern-argument form (Ruby 2.5+)

Since Ruby 2.5, these methods accept one argument and check it with ===, so classes, ranges and regexes work.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...