Ruby: Using all? with empty collection

Posted . Visible to the public.

Enumerable#all? Show archive.org snapshot returns true for an empty collection. This totally makes sense but you have to think about it when making assumptions on relations which might be empty.

[].all?(&:will_never_be_called_here) => true

Example with empty collection

class Researcher < ActiveRecord::Base
  has_many :papers
end

class Paper
  validates :topic, inclusion: { in: ['computer_science', 'mathematics', 'economy'] }
end

Easy goal: Delete all researches who write only about computer science.

# Bad (deletes researchers with no topic at all)
Researcher.find_each |researcher| do
  if researcher.papers.all? { |topic| topic == 'computer_science' }
    researcher.destroy!
  end
end

# Good
Researcher.find_each |researcher| do
  if researcher.papers.present? && researcher.papers.all? { |topic| topic == 'computer_science' }
    researcher.destroy!
  end
end

There are more methods in Enumerable (returning boolean values) where you might need to think twice with empty collections.

Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2018-01-11 08:41)