2011-12-21 58 views
0

是否可以將我自己的方法附加到另一個類,在有限的區域中?將方法附加到ruby中的受限上下文中的另一個類

如果是這樣,任何人都可以告訴我一個更好的做法,或者是否應該使用類似deligate這樣做?

的情況是這樣的:在接收,產生和傳遞出實例類B的, 我要附加一些方法在那些b S,不留這些新方法的外部訪問類A類A

回答

0

這些被稱爲singleton methods。您可以將方法添加到任何對象,隻影響該實例,而不是它創建的整個類。

some_object = Whatever.new 
other_object = Whatever.new 

class << some_object 
    def another_method 
    ... 
    end 
end 

some_object.another_method # works 
other_object.another_method # error: no such method another_method 

您還可以使用define_singleton_method

some_object.define_singleton_method(:foo) do |arg1, arg2| 
    puts "Called with #{arg1} and #{arg2}" 
end 

some_object.foo(7, 8) 

還有instance_eval,但你的想法;)

+0

謝謝。但是,僅此一項仍然無法隱藏在外部調用方法。在傳遞'b's之前''取消'這些方法似乎很乏味但可能。 – Jokester 2011-12-21 06:08:01

0

你可以寫在B類,它接受一個目的是:私有方法一個參數並使用instance_variable_getinstance_variable_setsend來訪問所需對象的任何數據。雖然這很醜陋。

相關問題