28

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

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

4

2 回答 2

50

在一个模块中:

当您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
于 2009-06-08T23:16:19.427 回答
0

简短的总结... 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
于 2009-06-08T04:25:19.617 回答