gpt4 book ai didi

ruby - "monkey-patch"Ruby 的基类有更好的方法吗?

转载 作者:太空宇宙 更新时间:2023-11-03 16:10:36 25 4
gpt4 key购买 nike

对于我正在编写的几何库,我想支持向量与标量的乘法,只需定义 Vector#* 即可轻松实现 vector * scalar方法。但是,要支持 scalar * vector,所有 Fixnum#*Bignum#*Float#* 方法都必须被猴子修补。我为这些类中的每一个使用以下代码来实现这一点:

class Fixnum
old_times = instance_method(:'*')

define_method(:'*') do |other|
case other
when Geom3d::Vector
Geom3d::Vector.new(self * other.dx, self * other.dy, self * other.dz)
else
old_times.bind(self).(other)
end
end
end

class Bignum
#...
end

class Float
#...
end

我想知道是否有更好的方法来完成此操作,或者这样做是否存在任何潜在问题?

最佳答案

看看 Ruby 的 coerce feature .

关于ruby - "monkey-patch"Ruby 的基类有更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4708746/

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