Read more

Ruby: Using all? with empty collection

Emanuel
January 11, 2018Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Emanuel to makandra dev (2018-01-11 09:41)