Ruby/Class/Operator

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

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

Define operator for class

class TriMatrix
  def initialize
    @store = []
  end
  def [](x,y)
    if x > y
      index = (x*x+x)/2 + y
      @store[index]
    else
      raise IndexError
    end
  end
  def []=(x,y,v)
    if x > y
      index = (x*x+x)/2 + y
      @store[index] = v
    else
      raise IndexError
    end
  end
end
 
t = TriMatrix.new
t[3,2] = 1
puts t[3,2]  # 1



Define plus operator

  class MyClass
    def initialize(string)
      @value = string.gsub(/[aeiou]/, "*")
    end
    def +(other)
      MyClass.new(self.to_s + other.to_s)
    end
    def to_s
      @value
    end
    def inspect
      @value
    end
  end
  a = MyClass.new("damn ")
  a += "shame"