gpt4 book ai didi

ruby - 了解强制

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:53 24 4
gpt4 key购买 nike

我已经提交了 pull request ,它修改了 Matrix 类,以便可以用实数执行加法:

矩阵[ [25, 93], [-1, 66] ] + 5

Matrix 类有一个方法+(),在这种情况下会调用它。

我还希望用户能够将操作顺序更改为

5 + 矩阵[ [25, 93], [-1, 66] ]

矩阵 class似乎支持 *() 方法的这种操作顺序,我不确定如何为 +() 方法实现这一点。

最佳答案

强制使用 coerce 方法处理。此方法将返回要重试给定运算符/方法的两个元素。 Matrix 定义 coerce 如下:

def coerce(other)
case other
when Numeric
return Scalar.new(other), self
else
raise TypeError, "#{self.class} can't be coerced into #{other.class}"
end
end

但请注意,它并没有改变操作数的顺序,而是将数值转换为 Scalar 类。因此,看到 5 + Matrix[...] 的 ruby​​ 将执行 Scalar.new(5) + Matrix[...]

Scalar 类在同一文件中定义,并定义了自己的一组运算符,包括 + 和“-”。所以你需要做的是摆脱行 Scalar.Raise ErrOperationNotDefined, "+", @value.class, other.class 并在此处强制执行你的代码,例如 other + self

关于ruby - 了解强制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24984252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com