gpt4 book ai didi

ruby - 为什么 Ruby 精化只修改类,而不修改模块?

转载 作者:数据小太阳 更新时间:2023-10-29 07:35:41 27 4
gpt4 key购买 nike

Ruby docs on refinements state :

Refinements only modify classes, not modules so the argument must be a class.

这是为什么?

可以对模块进行猴子修补:

module MyModule
def my_method
"hello"
end
end

include MyModule
puts my_method # => hello

module MyModule
def my_method
"goodbye"
end
end

puts my_method # => goodbye

我敢肯定这不是一个好主意,但如果您可以限制这种猴子补丁的范围,它可能不会那么糟糕。那你为什么不能?

最佳答案

模块的改进与类的改进一样有用。考虑如何

module Foobar
refine Enumerable
def all_zero?; all? &:zero? end
end
end

比直接猴子修补更礼貌:

module Enumerable
def all_zero?; all? &:zero? end
end

有一个 implementation issue带有精炼模块,seems to be solved by now .

关于ruby - 为什么 Ruby 精化只修改类,而不修改模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071443/

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