Custom class based range : Comparable « Collections « Ruby






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))

 








Related examples in the same category

1.Comparable module can provide the other basic comparison operators and between?.
2.include Comparable
3.Comparison operator