Ruby/Collections/Comparable

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Comparable module can provide the other basic comparison operators and between?.

class Song
  include Comparable
  attr_accessor :length
  def <=>(other)
    @length <=> other.length
  end
  def initialize(song_name, length)
    @song_name = song_name
    @length = length
  end
end
a = Song.new("Rock around the clock", 143)
b = Song.new("Bohemian Rhapsody", 544)
c = Song.new("Minute Waltz", 60)
# Here are the results of including the Comparable module:
a < b
b >= c
c > a
a.between?(b,c)



Comparison operator

class CD
  include Comparable
  @@plays = 0
  attr_reader :name, :artist, :duration
  attr_writer :duration
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
    @plays    = 0
  end
  def to_s
    "CD: #@name--#@artist (#@duration)"
  end
  def <=>(other)
    self.duration <=> other.duration
  end
end



Custom class based range

  class MyCapacity
    include Comparable
    attr :volume
    def initialize(volume)  # 0..9
      @volume = volume
    end
    def inspect
      "#" * @volume
    end
    def <=>(other)
      self.volume <=> other.volume
    end
    def succ
      raise(IndexError, "Volume too big") if @volume >= 9
      MyCapacity.new(@volume.succ)
    end
  end
medium_volume = MyCapacity.new(4)..MyCapacity.new(7)
medium_volume.to_a
medium_volume.include?(MyCapacity.new(3))



include Comparable

class CD
  include Comparable
  @@plays = 0
  attr_reader :name, :artist, :duration
  attr_writer :duration
  def initialize(name, artist, duration)
    @name     = name
    @artist   = artist
    @duration = duration
    @plays    = 0
  end
  def to_s
    "CD: #@name--#@artist (#@duration)"
  end
  def duration_in_minutes=(new_duration)
    @duration = (new_duration*60).to_i
  end
  def play
    @plays  += 1  
    @@plays += 1
    "This  CD: #@plays plays. Total #@@plays plays."
  end
  def inspect
    self.to_s
  end
  def <=>(other)
    self.duration <=> other.duration
  end
end
d = CD.new("A", "B", 1)
d.to_s