use*_*812 15 ruby oop access-specifier
我可以创建一个可以通过类方法调用的私有实例方法吗?
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
Run Code Online (Sandbox Code Playgroud)
抱歉,如果这是一个非常基本的问题,但我无法以谷歌的方式找到解决方案.
Sam*_*uel 18
使用私有或受保护的实际上并没有在Ruby中做那么多.您可以在任何对象上调用send并使用它拥有的任何方法.
class Foo
def Foo.bar(my_instance, n)
my_instance.send(:plus, n)
end
end
Run Code Online (Sandbox Code Playgroud)
你可以像塞缪尔所展示的那样做,但它确实绕过了OO检查......
在Ruby中,您只能在同一个对象上发送私有方法,并且只能保护同一个类的对象.静态方法驻留在元类中,因此它们位于不同的对象(也是不同的类)中 - 因此您无法使用私有或受保护的方式.
你也可以用 instance_eval
class Foo
def self.bar(my_instance, n)
my_instance.instance_eval { plus(n) }
end
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11215 次 |
| 最近记录: |