类<< Ruby中的自我成语 [英] class << self idiom in Ruby

查看:113
本文介绍了类<< Ruby中的自我成语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class << self Ruby 中做什么?

推荐答案

首先,class << foo语法打开foo的单例类(特征类).这使您可以专门化在该特定对象上调用的方法的行为.

First, the class << foo syntax opens up foo's singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.

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对象(在类或模块体内的类或模块本身).通常,这用于定义类/模块(静态")方法:


Now, to answer the question: class << self opens up self's singleton class, so that methods can be redefined for the current self object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods:

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打开该对象的单例类.一种用途是实现穷人的状态机:


When inside a function definition, self refers to the object the function is being called with. In this case, class << self opens the singleton class for that object; one use of that is to implement a poor man's state machine:

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方法(该方法调用可重定义的process_hook)时,行为都会根据其所处的状态而变化.

So, in the example above, each instance of StateMachineExample has process_hook aliased to process_state_1, but note how in the latter, it can redefine process_hook (for self only, not affecting other StateMachineExample instances) to process_state_2. So, each time a caller calls the process method (which calls the redefinable process_hook), the behaviour changes depending on what state it's in.

这篇关于类&lt;&lt; Ruby中的自我成语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆