(Ruby,Rails) 模块和库中 SELF 的上下文......? [英] (Ruby,Rails) Context of SELF in modules and libraries...?
问题描述
关于在模块或库中使用SELF"的快速问题.基本上什么是SELF"的范围/上下文,因为它与模块或库有关,以及如何正确使用它?有关我正在谈论的内容的示例,请查看与restful_authentication"一起安装的AuthenticatedSystem"模块.
Quick question regarding the use of "SELF" inside a module or library. Basically what is the scope/context of "SELF" as it pertains to a module or library and how is it to be properly used? For an example of what I'm talking about, check out the "AuthenticatedSystem" module installed with "restful_authentication".
注意:我知道在其他语言中self"等同于this"以及self"如何在类/对象上操作,但是在模块/库的上下文中,self"没有任何意义.那么,在没有类的模块中,self 的上下文是什么?
NOTE: I'm aware that 'self' equates to 'this' in other languages and how 'self' operates on a class/object, however in the context of a module/library there is nothing to 'self'. So then what is the context of self inside something like a module where there is no class?
推荐答案
在模块中:
当您在实例方法中看到 self
时,它指的是包含该模块的类的实例.
When you see self
in an instance method, it refers to the instance of the class in which the module is included.
当您在实例方法之外看到 self
时,它指的是模块.
When you see self
outside of an instance method, it refers to the module.
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,Rails) 模块和库中 SELF 的上下文......?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!