gpt4 book ai didi

ruby-on-rails - Ruby 的混合链接无法正常工作

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

我在 Windows 上使用 Ruby 1.9.3。所以我想通过 Kernel 类添加在控制台中可用的方法。启动控制台。

module Foo
def bar
puts "Method is in scope!!!"
end
end

将其添加到Kernel(它是Object 类的一部分)

irb(main):008:0> Kernel.send(:include, Foo)
=> Kernel
irb(main):009:0> bar
"NameError: undefined local variable or method `bar' for main:Object"
# did not work, we need to re-include Kernel in Object class
irb(main):010:0> Object.send(:include, Kernel)
=> Object
irb(main):011:0> bar
Method is in scope!!!
=> nil
irb(main):012:0>

这应该只适用于 Kernel.send(:include, Foo) 还是我错了?我错过了什么吗?

最佳答案

是的,在这种情况下,您应该直接扩展 Object。但如果您愿意,您可以扩展 Kernel,只是不要忘记再次将其重新包含到 Object 中。

module Foo
def bar
puts "Method is in scope!!!"
end
end

Kernel.send :include, Foo
# bar at this point will generate error

Object.send :include, Kernel
bar
# >> Method is in scope!!!

另请参阅 this answer以获得更详尽的解释。

关于ruby-on-rails - Ruby 的混合链接无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11030129/

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