【问题标题】:Calling self.private_method in Ruby not throwing error?在 Ruby 中调用 self.private_method 不会引发错误?
【发布时间】:2013-11-15 10:54:42
【问题描述】:

我认为在调用私有方法时放置显式接收器是不可接受的。好吧,我在 Ruby 2.0 中做了这个,我可以得到结果:

class Test
  def public_method
    self.set_size=10
  end

  def return_size
    @size
  end

  private

  def set_size=(size)
    @size = size
  end

 end

test = Test.new
test.public_method
p test.return_size

这是为什么?

【问题讨论】:

  • 您为什么认为这是不可接受的?我看起来可以接受。
  • 不是我想的,它在文档中:Private methods cannot be called with an explicit receiver - the receiver is always self. This means that private methods can be called only in the context of the current object; you cannot invoke another object's private methods.
  • @HommerSmith:你在 self 上调用方法......这没有什么问题。
  • 访问限制。不是语法限制。我会将其解释为“......不能用显式接收器调用 self 以外的,因为接收器始终是 self”
  • @Linuxios 即使self 不是setter 方法也会挂起。如果我们发送的方法是 setter,那么显式接收器(self 或其他)是正确的。

标签: ruby


【解决方案1】:

私有设置器可以使用self 的显式接收器调用。事实上,他们必须被一个明确的接收者调用,因为否则他们不能在全部被调用,因为

foo = bar

是对局部变量的赋值,而不是方法调用。

【讨论】:

  • 我认为需要澄清set_size 是一种方法。一种方法是在前面加上self.;另一个是send(:set_size=, 10),它没有明确的接收者。
【解决方案2】:

你是对的,除了一件事...... setter (def method=) 可以用 self 的显式接收者调用,这样你就可以调用私有 setter。

所以,实际上如果你打算这样做:

class Test
  def public_method
    self.say_hi
  end

  def return_size
    @size
  end

  private

  def say_hi
    puts "oh hay there"
  end

 end
test = Test.new
test.public_method
test.return_size

它会抛出一个private method say_hi called for..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多