Ruby Koans about_methods 第 119 行如何在 IRB 中的私有方法上获取错误

Ruby Koans about_methods line 119 how to get error on a private method in IRB

我在 IRB 中尝试 运行 这种方法,但没有得到任何结果。只是新命令的新行。我知道这是一个私有方法,但我不明白人们是如何得到所需的错误的。

def my_private_method
    "a secret"
end
private :my_private_method

和预期结果:(NoMethodError)/private method/

def test_calling_private_methods_with_an_explicit_receiver
    exception = assert_raise(__) do
        self.my_private_method
    end
    assert_match /__/, exception.message
end

如果您只是将此方法粘贴到 irb 会话中而不将其包含到 class 中,那么您是在 Object 范围内定义该方法:

2.2.1 :001 > def my_private_method 2.2.1 :002?> "a secret" 2.2.1 :003?> end => :my_private_method 2.2.1 :004 > private :my_private_method => Object 2.2.1 :005 > my_private_method => "a secret"

之所以可以调用私有方法,是因为调用方法时,你还在Object的范围内。这是有道理的......你应该能够从同一范围内调用私有方法。

class 中的私有方法不能被另一个 class 实例调用。这是一个可能有帮助的示例:

class PrivateMethodClass

  def my_private_method
    "a secret"
  end

  def puts_my_private_method
    puts my_private_method
  end

  private :my_private_method
end

class AnotherClass

  def that_private_method
    PrivateMethodClass.new.my_private_method
  end
end

将上面的内容粘贴到 irb 中,然后为每个 class 创建实例并尝试调用它们的方法。注意PrivateMethodClass个实例可以调用:puts_my_private_method并执行,但是AnotherClass个实例不能成功调用:that_private_method.