2011-12-21 29 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来访问所需对象的任何数据。虽然这很丑陋。

相关问题