Ruby条件分配和私有方法

Ruby条件分配和私有方法

本文介绍了Ruby条件分配和私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,似乎正在从类外部评估||=运算符.

From the code below, it appears the ||= operator is being evaluated from outside of the class.

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)

> | =条件赋值运算符的正式扩展上引用已接受的答案:

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

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

Rewriting the baz method as self.bar = self.bar || 'baz' does not raise the error.

我正在寻找有关 how 为什么行为的确切答案,因为这似乎违反直觉.

I am looking for a definitive answer on how and why Ruby is behaving in this way, since it seems counter-intuitive.

此行为出现在Ruby 1.9.3、2.0.0和2.1.2版本中,这使我相信这不是错误.

This behaviour is present on Ruby versions 1.9.3, 2.0.0 and 2.1.2, which leads me to believe this is not a bug.

推荐答案

这看起来像是 bug .

更新: bug 已修复在主干中,并且计划向后移植到2.1和2.0 .

UPDATE: The bug was fixed in trunk, and is slated for back porting to 2.1 and 2.0.

请注意,这个问题比这更笼统,对于 all 缩写分配,它是有问题的,而不仅仅是条件缩写分配:

Note that the problem is more general than that, it is broken for all abbreviated assignments, not just conditional abbreviated assignments:

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)

这篇关于Ruby条件分配和私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:00