class << self在 Ruby 中做什么?
class << self
首先,class << foo语法打开了foo的单例类(eigenclass)。这允许您专门化在该特定对象上调用的方法的行为。
class << foo
foo
a = 'foo' class << a def inspect '"bar"' end end a.inspect # => "bar" a = 'foo' # new object, new singleton class a.inspect # => "foo"
现在,回答这个问题:class << self打开self的单例类,以便可以为当前self对象重新定义方法(在类或模块主体内是类或模块 本身 )。通常,这用于定义类/模块(“静态”)方法:
self
class String class << self def value_of obj obj.to_s end end end String.value_of 42 # => "42"
这也可以写成简写:
class String def self.value_of obj obj.to_s end end
甚至更短:
def String.value_of obj obj.to_s end
在函数定义中,self指的是调用函数的对象。在这种情况下,class << self打开该对象的单例类;一种用途是实现穷人的状态机:
class StateMachineExample def process obj process_hook obj end private def process_state_1 obj # ... class << self alias process_hook process_state_2 end end def process_state_2 obj # ... class << self alias process_hook process_state_1 end end # Set up initial state alias process_hook process_state_1 end
因此,在上面的示例中,每个实例StateMachineExample都process_hook别名为process_state_1,但请注意在后者中,它如何重新定义process_hook(self仅用于,不影响其他StateMachineExample实例)为process_state_2。因此,每次调用者调用该process方法(调用 redefinable process_hook)时,行为都会根据它所处的状态而改变。
StateMachineExample
process_hook
process_state_1
process_state_2
process