Comparable and Enumerable in your own class
Comparable and <=>
A class that defines <=> and includes Comparable gets <, >, ==, between?, clamp and a working min and max:
class Box include Comparable attr_reader :n def initialize(n) @n = n end def <=>(other) n <=> other.n end end p Box.new(2) > Box.new(1)
ruby -e 'class Box; include Comparable; def initialize(n) = @n = n; attr_reader :n; def <=>(o) = @n <=> o.n; end; p Box.new(2) > Box.new(1)'
true
Only <=> is written by hand. The module defines the rest in terms of it, so there is one comparison rule and no chance of < disagreeing with sort. <=> returns -1, 0 or 1, and nil for two values that cannot be compared.
Enumerable and each
The same trick works for iteration. Define each and include Enumerable, and the class gains map, select, sum, sort, first, min_by and the rest of the toolbox:
class Bag include Enumerable def each yield 1 yield 2 end end p(Bag.new.map { _1 * 2 }) p Bag.new.sum p Bag.new.select(&:even?)
ruby -e 'class Bag; include Enumerable; def each; yield 1; yield 2; end; end; p(Bag.new.map { _1 * 2 }); p Bag.new.sum; p Bag.new.select(&:even?)'
[2, 4]
3
[2]
each has to yield the items and nothing else: no return value matters, and a caller that passes a block gets the items one at a time. A collection that wraps an array usually delegates: @items.each { |item| yield item }, or @items.each(&block) with &block in the signature.
What you get for free
Two examples of the payoff, using the class above: a comparison that reads like a sentence, and a sorted collection with the smallest value:
ruby -e 'class Box; include Comparable; def initialize(n) = @n = n; attr_reader :n; def <=>(o) = @n <=> o.n; end; p [Box.new(3), Box.new(1)].min.n; p Box.new(2).clamp(Box.new(1), Box.new(3)).n'
1
2
ruby -e 'class Bag; include Enumerable; def each; yield 1; yield 2; end; end; p Bag.new.sort; p Bag.new.first; p Bag.new.min'
[1, 2]
1
1
None of those methods were written. That is the difference between a class that holds a collection and a collection: the second one speaks the language the rest of Ruby already uses.
What to watch for
Comparable gives == from
<=>, but not
eql? and not hash. A box
used as a hash key still needs those two, which is the point of
lesson 2.6
and, later, lesson
6.9.
An each that yields lazily from a file or a
socket can be consumed only once. A caller that maps and then selects
reads the stream twice and gets nothing the second time; read it into an
array first, or design the class to be re-iterable.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a class have to define before
include Comparablegives it<,>andbetween??Answer
<=>
Comparable builds every comparison from <=>, so there is one comparison rule.
-
What does this program print?
class Box include Comparable attr_reader :n def initialize(n) @n = n end def <=>(other) n <=> other.n end end p Box.new(2) > Box.new(1)Answer
true
Comparable defines > from <=>, and 2 is greater than 1.
-
What does this program print?
class Bag include Enumerable def each yield 1 yield 2 end end p(Bag.new.map { _1 * 2 }) p Bag.new.sum p Bag.new.select(&:even?)Answer
[2, 4] / 3 / [2]
map, sum and select all come from Enumerable and run on the two yielded items.
-
What does this program print?
class Box include Comparable attr_reader :n def initialize(n) @n = n end def <=>(other) n <=> other.n end end p [Box.new(3), Box.new(1)].min.n p Box.new(2).clamp(Box.new(1), Box.new(3)).nAnswer
1 / 2
min and clamp use <=> too, and 2 sits between 1 and 3.
-
What does an
eachmethod have to do to work with Enumerable?Answer
Yield each item to the block, one at a time
The return value does not matter; the yielded items are the collection.
-
What does this program print?
class Bag include Enumerable def each yield 1 yield 2 end end p Bag.new.sort p Bag.new.first p Bag.new.minAnswer
[1, 2] / 1 / 1
sort, first and min all read the yielded items through Enumerable.
-
What does Comparable not give a class?
Answer
eql?andhash, which a hash key still needsThat is why a value object used as a hash key defines eql? and hash as well.
-
What does this program print?
class Bag include Enumerable def each [3, 1].each { yield _1 } end end p Bag.new.sortAnswer
[1, 3]
Delegating to an array each yields the same two items, and sort orders them.
-
A class includes Enumerable but defines no
each. What happens onmap?Answer
NoMethodError, because there is no each to read
Every Enumerable method is built on each, so the missing each is the failure.
-
An
eachyields lines read from a socket. What does a second pass over the collection see?Answer
Nothing, because the stream was consumed by the first pass
A one-shot stream has to be read into an array first, or the class has to be re-iterable.
Article author: Arthur Isaev