关于在模块或库中使用“SELF”的快速问题。基本上,“SELF”的范围/上下文是什么,因为它属于模块或库,如何正确使用它?有关我所说内容的示例,请查看随“restful_authentication”一起安装的“AuthenticatedSystem”模块。
注意:我知道“self”在其他语言中等同于“this”,以及“self”如何在类/对象上运行,但是在模块/库的上下文中,“self”没有任何意义。那么在没有类的模块之类的东西中,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
关于ruby-on-rails - (Ruby,Rails)模块和库中 SELF 的上下文......?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/963378/