0Pricing
Ruby Academy · Lesson

Comparable and Enumerable

Standard mixins.

Standard Mixins

Ruby ships powerful modules you can mix into your own classes. Two stars are Comparable and Enumerable. Each gives you many methods in exchange for implementing just one.

puts Comparable.instance_methods.sort.inspect

Comparable Needs <=>

Comparable requires you to define the spaceship operator <=>, which returns -1, 0, or 1. In return you get <, <=, ==, >, >=, and between?.

class Weight
  include Comparable
  attr_reader :grams
  def initialize(g); @grams = g; end
  def <=>(other); grams <=> other.grams; end
end
puts Weight.new(50) < Weight.new(80)

All lessons in this course

  1. Defining Modules
  2. include and extend
  3. Comparable and Enumerable
  4. prepend and Method Resolution
← Back to Ruby Academy