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.inspectComparable 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
- Defining Modules
- include and extend
- Comparable and Enumerable
- prepend and Method Resolution