有人可以解释一下 class <<自我对我? [英] Can someone please explain class << self to me?
问题描述
我是第一次进入 Rails 编程,在查看我下载的一些库的代码时,我偶尔会注意到代码:
I'm jumping into rails programming for the first time and while looking at the code for some libraries I've downloaded, I occasionally notice the code:
class << self
def func
stuff
end
end
我试过在网上搜索解释,但是 <<从大多数有用的搜索引擎中删除,因此它最终只搜索 class self,这不是很有用.任何见解将不胜感激.
I've tried searching the web for an explanation, but the << gets stripped from most useful search engines, so it ends up just searching for class self, which isn't very useful. Any insight would be appreciated.
推荐答案
在 Ruby 中,class <<foo
打开foo
引用的对象的单例类.在 Ruby 中,每个对象都有一个与之关联的单例类,它只有一个实例.这个单例类包含特定于对象的行为,即单例方法.
In Ruby, class << foo
opens up the singleton class of the object referenced by foo
. In Ruby, every object has a singleton class associated with it which only has a single instance. This singleton class holds object-specific behavior, i.e. singleton methods.
所以,class <<self
打开了 self
的单例类.self
是什么,当然取决于你所处的环境.例如,在模块或类定义体中,它是模块或类本身.
So, class << self
opens up the singleton class of self
. What exactly self
is, depends on the context you are in, of course. In a module or class definition body, it is the module or class itself, for example.
如果您使用单例类的目的只是定义单例方法,那么实际上有一个快捷方式:def foo.bar
.
If all you are using the singleton class for, is defining singleton methods, there is actually a shortcut for that: def foo.bar
.
以下是如何使用单例方法提供一些与特定实例没有任何关联的过程"的示例:
Here's an example of how to use singleton methods to provide some "procedures" which don't really have any association with a particular instance:
class << (Util = Object.new)
def do_something(n)
# ...
end
end
Util.do_something(n)
这篇关于有人可以解释一下 class <<自我对我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!