类<<Ruby 中的自我习语 [英] class &lt;&lt; self idiom in Ruby

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

问题描述

class <<selfRuby 中做什么?

推荐答案

一、class <<foo 语法打开了 foo 的单例类(eigenclass).这允许您专门化对该特定对象调用的方法的行为.

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


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


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.

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

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