我可以创建一个可以被类方法调用的私有(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/