gpt4 book ai didi

ruby - 如何动态使用优化

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

试图理解这种“改进”业务。

我正在制作一个改进核心类的模块:

module StringPatch
refine String do
def foo
true
end
end
end

然后一个类来使用细化

class PatchedClass
end

PatchedClass.send :using, StringPatch

我收到这个错误:

RuntimeError: Module#using is not permitted in methods

我怎样才能使这项工作?我正在尝试仅在特定范围内动态修补核心类。我想让补丁在类和实例范围内可用。

最佳答案

据我所知,细化一直持续到脚本结束时 using在 main 中,直到当前类/模块定义结束时 using在类或模块中。

module StringPatch
refine String do
def foo
true
end
end
end

class PatchedClass
using StringPatch
puts "test".foo
end

class PatchedClass
puts "test".foo #=> undefined method `foo' for "test":String (NoMethodError)
end

这意味着如果您设法动态调用 using在类或模块上,它的效果将被直接移除。

您不能使用 refine在方法中,但您可以在经过优化的类中定义方法:

class PatchedClass
using StringPatch
def foo
"test".foo #=> true
end
end

class PatchedClass
def bar
"test".foo
end
end

patched = PatchedClass.new
puts patched.foo #=> true
puts patched.bar #=> undefined method `foo' for "test":String (NoMethodError)

对于你的问题,这个discussion可能很有趣。看起来改进是有意限制的,但我不知道为什么:

Because refinement activation should be as static as possible.

关于ruby - 如何动态使用优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41027886/

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