(Ruby,Rails)SELF在模块和库中的上下文……?

关于在模块或库中使用“SELF”的快速问题。 基本上什么是“SELF”的范围/上下文,因为它与模块或库有关,如何正确使用? 有关我正在讨论的示例,请查看安装了“restful_authentication”的“AuthenticatedSystem”模块。

注意:我知道’self’在其他语言中等同于’this’以及’self’如何在类/对象上操作,但是在模块/库的上下文中没有“自我”。 那么,在没有类的模块中,自我的上下文是什么?

在一个模块中:

当您在实例方法中看到self时,它指的是包含该模块的类的实例。

当您在实例方法之外看到self ,它指的是模块。

 module Foo def a puts "a: I am a #{self.class.name}" end def Foo.b puts "b: I am a #{self.class.name}" end def self.c puts "c: I am a #{self.class.name}" end end class Bar include Foo def try_it a Foo.b # Bar.b undefined Foo.c # Bar.c undefined end end Bar.new.try_it #>> a: I am a Bar #>> b: I am a Module #>> c: I am a Module 

如需简短摘要… http://paulbarry.com/articles/2008/04/17/the-rules-of-ruby-self

self也用于添加类方法(或C#/ Java人员的静态方法)。 以下片段是将一个名为do_something的方法添加到当前类对象(静态)…

 class MyClass def self.do_something # class method # something end def do_something_else # instance method end end