为什么在 Ruby 中使用数组联合运算符 |= 时必须在访问器上显式调用 self ? [英] Why must I explicitly call self on accessor when using the Array union operator |= in Ruby?

查看:36
本文介绍了为什么在 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"

这篇关于为什么在 Ruby 中使用数组联合运算符 |= 时必须在访问器上显式调用 self ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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