我的目標是實現數學向量的加法運算符。我需要添加標量,數組到MyVector的能力。此外,我需要的操作是可交換的,所以我可以將數字添加到MyVector和MyVector來編號。我按照這裏的配方In Ruby, how does coerce() actually work?和其他一些互聯網資源來定義下面的+運算符。未按預期方式調用紅寶石脅迫方法
class MyVector
def initialize(x,y,z)
@x, @y, @z = x, y, z
end
def +(other)
case other
when Numeric
MyVector.new(@x + other, @y + other, @z + other)
when Array
MyVector.new(@x + other[0], @y + other[1], @z + other[2])
end
end
def coerce(other)
p "coercing #{other.class}"
[self, other]
end
end
t = MyVector.new(0, 0, 1)
p t + 1
p 1 + t
p t + [3 , 4 , 5]
p [3 , 4 , 5] + t
和輸出
#<MyVector:0x007fd3f987d0a0 @x=1, @y=1, @z=2>
"coercing Fixnum"
#<MyVector:0x007fd3f987cd80 @x=1, @y=1, @z=2>
#<MyVector:0x007fd3f987cbf0 @x=3, @y=4, @z=6>
test.rb:26:in `<main>': no implicit conversion of MyVector into Array (TypeError)
顯然強制添加電話號碼,但似乎並沒有爲陣列工作時做的工作。相反,Array類的+方法似乎會被調用,它會嘗試將MyVector轉換爲Array,從而失敗。我的問題是,爲什麼MyVector的脅迫方法沒有被調用?
有沒有一種方法可以將交換數組添加到MyVector?也許可以擴展Array#+的定義? – Vineet 2014-10-19 21:01:35