为什么在 Ruby 中使用数组联合运算符 |= 时必须在访问器上显式调用 self ?

为什么在 Ruby 中使用数组联合运算符 |= 时必须在访问器上显式调用 self ?

问题描述:

以这个类为例:

 class MyClass
  attr_accessor :values, :uniq_values

  def initialize(value)
    self.uniq_values = ['default_value']
    self.values = ['default_value']
    copy_value(value)
    add_value(value)
  end

  def copy_value(value)
    uniq_values |= [value]
  end

  def add_value(value)
    values << value
  end

  def run
    puts "uniq_values: #{uniq_values}"
    puts "values: #{values}"
  end
end

obj = MyClass.new('poop')
obj.run

# Expect 'uniq_values' and 'values' to be the same
# OUTPUT:
#  uniq_values: ["default_value"]
#  values: ["default_value", "poop"]

我可以通过使用 self.uniq_values |= [value] 获得所需的输出,但是我希望 << 运算符是必要的以及.谁能解释一下区别?

I can get the desired output by using self.uniq_values |= [value], however I would expect that it would be necessary with the << operator as well. Can anyone explain the difference?

不一样.

值为方法调用,调用Array的:的方法.

values << value is method calling, which calls the method of :<< of Array.

虽然 uniq_values |= value 只是 uniq_values = uniq_values | 的捷径value,这里uniq_values会被解析为局部变量.

While uniq_values |= value is just the short cut of uniq_values = uniq_values | value, here uniq_values will be parsed as the local variable.

根据 文档:

"局部变量在解析器遇到分配,而不是在分配发生时"

"The local variable is created when the parser encounters the assignment, not when the assignment occurs"

"当使用方法赋值时,你必须始终有一个接收器.如果你没有接收器 Ruby 假设您要分配给本地变量"

"When using method assignment you must always have a receiver. If you do not have a receiver Ruby assumes you are assigning to a local variable"