Ruby/Class/Operator
Материал из Wiki.crossplatform.ru
Версия от 17:10, 26 мая 2010; (Обсуждение)
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"