ruby - 从 Ruby 中的类方法调用私有(private)实例方法

标签 ruby oop access-specifier

我可以创建一个可以被类方法调用的私有(private)实例方法吗?

class Foo
  def initialize(n)
    @n = n
  end
  private # or protected?
  def plus(n)
    @n += n
  end
end

class Foo
  def Foo.bar(my_instance, n)
    my_instance.plus(n)
  end
end

a = Foo.new(5)
a.plus(3) # This should not be allowed, but
Foo.bar(a, 3) # I want to allow this

如果这是一个非常初级的问题,我深表歉意,但我无法通过 Google 找到解决方案。

最佳答案

在 Ruby 中使用 private 或 protected 并没有那么多作用。您可以在任何对象上调用发送并使用它具有的任何方法。

class Foo
  def Foo.bar(my_instance, n)
    my_instance.send(:plus, n)
  end
end

关于ruby - 从 Ruby 中的类方法调用私有(private)实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/420813/

相关文章:

javascript - 单击后退按钮时加载微调器和显示消息

ruby-on-rails - Paypal-express gem,在开发中工作但不在生产中

php - 动态调用类方法参数

c# - 具有相同签名的委托(delegate)

ruby - 了解 Ruby 中的私有(private)方法

c++ - 使用 C++0x decltype 绕过访问说明符

ruby - 如何使用 fork 的 Ruby 进程进行进程间锁定?

ruby - 制作一个不是 gem(或其他类型)的 Ruby 项目

C# 静态作用域问题

java - Java 中的接口(interface) : cannot make implemented methods protected or private