The Ruby Programming Language

More Mixin

class Song
  include Comparable #a built-in mixin, requires me to define <=>
  attr_reader :duration #so I can access other.duration

  def initialize(name, artist, duration)
    @name = name
    @artist = artist
    @duration = duration
  end

  def <=>(other)
    return @duration <=> other.duration
  end

end

s1 = Song.new('a', 'a', 100)
s2 = Song.new('a', 'a', 200)

s1 <=> s2 # -1 
s1 < s2 #true
s1 > s2 #false

José M. Vidal .

11 of 11