【问题标题】:Ruby Conditional-Assignment and Private MethodsRuby 条件赋值和私有方法
【发布时间】:2014-07-26 08:12:50
【问题描述】:

从下面的代码来看,||= 运算符似乎是从类外部评估的。

class Foo
  attr_reader :bar

  def baz
    self.bar ||= 'baz'
  end

  private

  attr_writer :bar
end

puts Foo.new.baz
# => in `baz': private method `bar=' called for #<Foo:0x007fd9720829a8> (NoMethodError)

引用Official expansion of ||= conditional assignment operator 上已接受的答案:

In other words, the expansion c = c || 3 is (excluding bugs like in pre-1.9) correct.

baz 方法重写为self.bar = self.bar || 'baz' 不会引发错误。

我正在寻找关于 如何 以及 为什么 Ruby 以这种方式表现的明确答案,因为这似乎违反直觉。

这种行为出现在 Ruby 版本 1.9.3、2.0.0 和 2.1.2 上,这让我相信这不是错误。

【问题讨论】:

  • self.bar ||= 'baz' 表示self.bar || self.bar = 'baz'
  • @ArupRakshit 但它仍然没有解释为什么会引发错误,是吗?
  • @FarrukhAbdulkadyrov 这不是解释,那是给 OP 的。谁错误地解释了语法||=...
  • bug 在一小时前在后备箱中是 fixed,现在是 slated for back porting to 2.1 and 2.0

标签: ruby memoization


【解决方案1】:

这看起来像 bug

更新:bug 在后备箱中是 fixed,现在是 slated for back porting to 2.1 and 2.0

请注意,问题比这更普遍,它对于 所有 缩写赋值,而不仅仅是条件缩写赋值:

private def foo=(*) end
public  def foo; 0  end

self.foo =  42

self.foo += 42
# private method `foo=' called for main:Object (NoMethodError)

private :foo

self.foo += 42
# private method `foo' called for main:Object (NoMethodError)

【讨论】:

  • 是的。这是一个错误。我正要记录它。不过去之前就好了,我来过这里……
猜你喜欢
  • 2012-10-03
  • 2012-05-19
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 2015-12-08
相关资源
最近更新 更多