开发者

What mechanism is used to allow one to call methods defined in ruby root scope from that scope?

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜