2009-01-07 153 views
13

我可以創建可以通過類方法調用的私有實例方法嗎?從Ruby的類方法調用私有實例方法

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 

道歉,如果這是一個非常基本的問題,但我還沒有能夠谷歌我的方式解決方案。

+0

您應該解決你的問題,你有一個錯字。這些方法叫做bar或plus嗎? – Samuel 2009-01-07 15:54:52

回答

17

使用私有或保護真的不會在Ruby中做太多事情。您可以在任何對象上調用send,並使用它的任何方法。

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

你可以做到這一點塞繆爾顯示,但它實際上是繞過OO檢查...

在Ruby中,你只能在同一個對象發送私有方法和保護只對同一對象類。靜態方法駐留在一個元類中,因此它們處於不同的對象中(也是一個不同的類) - 所以你不能像使用private或protected一樣使用它。

6

你也可以使用instance_eval

class Foo 
    def self.bar(my_instance, n) 
    my_instance.instance_eval { plus(n) } 
    end 
end