使用什么机制允许人们从该范围调用在 ruby 根范围中定义的方法?
在 ruby 中,当在根作用域中定义一个方法时,可以从该作用域中调用它:
def foo
"foo"
end
foo #=> "foo"
在任何其他上下文中,情况并非如此:
class Bar
def foo
"foo"
end
foo #=> Error: No Method `foo` for class Bar
end
在设置 main
对象(一个Object
的实例)允许这种情况发生?
In ruby, when one defines a method in the root scope, it can be called from that scope:
def foo
"foo"
end
foo #=> "foo"
In any other context this is not the case:
class Bar
def foo
"foo"
end
foo #=> Error: No Method `foo` for class Bar
end
What mechanism is used in setting up the main
object (an instance of Object
) that allows this to happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这在 Ruby 中确实是一个特殊情况。如果您在全局范围内定义方法,它们实际上会在默认情况下包含在每个对象中的
Kernel
上定义。当没有定义其他上下文时,内核也在那里。由于类也继承自内核,因此在其上定义的方法也在类作用域中。
This is really special cased in Ruby. If you define methods in the global scope they get actually defined on
Kernel
which is included in every object by default.Kernel is also there when no other context is defined. Since Class inherits also from Kernel methods defined on it are also in scope in class scopes.
只是为了确认雅库布·汉普尔所说的话:
Just to confirm what Jakub Hampl said:
您应该将其定义为类方法 (
self
) 而不是实例方法You should define it as a class method (
self
) instead of instance method