我有自己的课
class Mutnum
attr_reader :value
def initialize(number)
raise TypeError, "Mutnum created on a non-numeric value" unless number.is_a? Numeric
@value = number
end
def ==(other)
if other.is_a? Mutnum
other.value == @value
else
@value == other
end
end
def set(newval)
@value = newval
end
def to_i
@value
end
def to_s
@value.to_s
end
def +(other)
if other.is_a? Numeric
@value + other
elsif other.is_a? Mutnum
Mutnum.new(@value + other.value)
end
end
def coerce(other)
if other.is_a? Numeric
[other, @value]
else
super
end
end
end
它本质上作为一个可变数字起作用(例如,我可以将一个传递给一个函数,在该函数中更改它,然后从它被调用的位置读取结果)。我正在使用它来减少在同一个应用程序中使用 wxRuby 和 gosu 的刺激性。
我想能够说Array#[Mutnum]
,[1,2,3,4][Mutnum.new(3)]
应该导致4
.
我应该向 Mutnum编辑添加哪些其他功能,以便可以将 Mutnums 用作数组索引\edit?我想我可以说[1,2,3,4][Mutnum.new(3).to_i]
,但是我必须做更多的调试。