TExcelTAD
Home › Ruby › Ruby Comparable & Enumerable Mixins

Ruby Comparable & Enumerable Mixins

Ruby's standard library contains two mixins that give your classes a huge amount of behaviour for very little code:

  • Comparable — define <=> once, get <, <=, ==, >, >=, between? and clamp.
  • Enumerable — define each once, get map, select, sort, min, sum, group_by and ~50 more.

This is the "contract" style of Ruby: implement one small method, receive a whole toolkit.

Comparable

The spaceship operator <=> must return a negative number, zero or a positive number (usually -1, 0, 1) — or nil when the two values can't be compared.

ruby · try it yourself
class Version
  include Comparable
  attr_reader :parts

  def initialize(text)
    @parts = text.split(".").map(&:to_i)
  end

  def <=>(other)
    parts <=> other.parts
  end

  def to_s = parts.join(".")
end

a = Version.new("1.10.0")
b = Version.new("1.9.3")
c = Version.new("2.0")

p a > b
p a == Version.new("1.10.0")
p b.between?(Version.new("1.0"), a)
puts [c, a, b].sort.join(" < ")
puts [c, a, b].max
puts b.clamp(a, c)
true
true
true
1.9.3 < 1.10.0 < 2.0
2.0
1.10.0

Comparing arrays with <=> compares element by element, which is exactly what version numbers need — "1.10.0" correctly beats "1.9.3", something plain string comparison gets wrong.

Notice that sort, max and min also work, because they use <=>.

A second Comparable example

ruby · try it yourself
class Money
  include Comparable
  attr_reader :cents

  def initialize(amount)
    @cents = (amount * 100).round
  end

  def <=>(other)
    return nil unless other.is_a?(Money)
    cents <=> other.cents
  end

  def to_s = format("$%.2f", cents / 100.0)
end

prices = [Money.new(4.99), Money.new(12), Money.new(0.5)]
puts prices.min
puts prices.sort.map(&:to_s).join(", ")
p Money.new(3) == Money.new(3.0)
p Money.new(1) == "1"
$0.50
$0.50, $4.99, $12.00
true
false

Returning nil for foreign objects makes == simply return false instead of crashing.

Enumerable

Include Enumerable and define an each method that yields every element:

ruby · try it yourself
class Playlist
  include Enumerable

  Song = Struct.new(:title, :artist, :seconds)

  def initialize
    @songs = []
  end

  def add(title, artist, seconds)
    @songs << Song.new(title, artist, seconds)
    self
  end

  def each(&block)
    @songs.each(&block)
    self
  end
end

list = Playlist.new
list.add("Blue Train", "Coltrane", 643)
    .add("So What", "Davis", 562)
    .add("Naima", "Coltrane", 261)

p list.map(&:title)
p list.select { |s| s.artist == "Coltrane" }.map(&:title)
p list.sum(&:seconds)
p list.min_by(&:seconds).title
p list.sort_by(&:title).map(&:title)
p list.group_by(&:artist).transform_values(&:count)
p list.include?(list.first)
p list.count
["Blue Train", "So What", "Naima"]
["Blue Train", "Naima"]
1466
"Naima"
["Blue Train", "Naima", "So What"]
{"Coltrane" => 2, "Davis" => 1}
true
3

Eight different collection operations, and the class only defines each. Struct (used for Song) is covered in the next lesson.

Enumerable with a generator

each doesn't have to walk over a stored array — it can compute elements on the fly:

ruby · try it yourself
class Countdown
  include Enumerable

  def initialize(from) = @from = from

  def each
    n = @from
    while n > 0
      yield n
      n -= 1
    end
  end
end

cd = Countdown.new(5)
p cd.to_a
p cd.select(&:odd?)
p cd.each_slice(2).to_a
p cd.reduce(:*)
p cd.lazy.map { |n| n * 10 }.first(2)
[5, 4, 3, 2, 1]
[5, 3, 1]
[[5, 4], [3, 2], [1]]
120
[50, 40]

Returning an Enumerator when there is no block

Built-in each methods return an enumerator when called without a block. Your class can do the same with enum_for:

ruby · try it yourself
class Team
  include Enumerable

  def initialize(*names) = @names = names

  def each
    return enum_for(:each) unless block_given?
    @names.each { |n| yield n }
  end
end

t = Team.new("Ada", "Linus", "Grace")
p t.each.with_index(1).map { |name, i| "#{i}.#{name}" }
p t.each.next
["1.Ada", "2.Linus", "3.Grace"]
"Ada"

What you get

Include You implement You receive (selection)
Comparable <=> < <= == > >= between? clamp
Enumerable each map select reject find reduce sum sort sort_by min max group_by partition each_slice to_a include? first count tally zip lazy …

Tip: For Enumerable#sort, min and max to work, the elements must be comparable. Combine both mixins: your collection includes Enumerable, its items include Comparable.

Test yourself

Which single method must a class define to use Comparable?

  1. ==
  2. <=>
  3. compare
  4. <

Which method must a class define to use Enumerable?

  1. map
  2. to_a
  3. each
  4. next

What should <=> return when the objects cannot be compared?

  1. 0
  2. false
  3. nil
  4. -1