未按预期调用ruby强制方法
我的目标是实现数学向量的加法运算符。我需要向MyVector添加标量和数组的能力。我还需要这个操作是可交换的,这样我就可以将数字添加到MyVector,将MyVector添加到数字。我按照这里的食谱和其他一些互联网资源定义了以下+操作符未按预期调用ruby强制方法,ruby,arrays,operators,coercion,Ruby,Arrays,Operators,Coercion,我的目标是实现数学向量的加法运算符。我需要向MyVector添加标量和数组的能力。我还需要这个操作是可交换的,这样我就可以将数字添加到MyVector,将MyVector添加到数字。我按照这里的食谱和其他一些互联网资源定义了以下+操作符 class MyVector def initialize(x,y,z) @x, @y, @z = x, y, z end def +(other) case other when Numeric
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)
#
“强制Fixnum”
#
#
test.rb:26:in`:没有将MyVector隐式转换为数组(TypeError)
显然,强制在添加数字时起作用,但在数组中似乎不起作用。相反,Array类上的+方法似乎被调用,它试图将MyVector转换为Array,但失败了。我的问题是,为什么MyVector的强制方法没有被调用 Ruby强制似乎只适用于
Fixnum
类型,因此在您的情况下不支持Array
。您看到的错误消息“没有将MyVector隐式转换为数组(TypeError)”,是由ruby Array的内置+方法生成的。强制执行
对数值类型执行强制。数组
不是数字类型<代码>数组#+不是加法,它是串联,它的行为不同于数字加法,例如[1,2,3]+[4,5,6]
与[4,5,6]+[1,2,3]有没有一种方法可以对MyVector执行交换数组加法?也许可以扩展数组#+的定义?