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开发者_如何学Python this to happen?
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:
def foo
"Debugging: self is #{self.inspect}"
end
foo # => "Debugging: self is main"
class Bar
def goo
foo
end
end
Bar.new.goo # => "Debugging: self is #<Bar:0x1513cc0>"
You should define it as a class method (self
) instead of instance method
class Bar
def self.foo
"foo"
end
foo
#=> "foo"
end
精彩评论