在运行时将实例方法设为私有
在将该对象注册到另一个对象后,我需要将一些实例方法设为私有。
我不想冻结对象,因为它必须保持可编辑状态,只有较少的function。 而且我不想取消这些方法,因为它们是在内部使用的。
我需要的是:
class MyClass def my_method puts "Hello" end end a = MyClass.new b = MyClass.new a.my_method #=> "Hello" a.private_instance_method(:my_method) a.my_method #=> NoMethodError b.my_method #=> "Hello"
有任何想法吗?
什么是公开的, 每个class级的私人是什么。 但是每个对象都有自己的类:
class Foo private def private_except_to_bar puts "foo" end end class Bar def initialize(foo) @foo = foo.dup class << @foo public :private_except_to_bar end @foo.private_except_to_bar end end foo = Foo.new Bar.new(foo) # => "foo" foo.private_except_to_bar # => private method `private_except_to_bar' called for # (NoMethodError)
但是你好。 考虑以下选择:
- 只需将方法公之于众。
- 探索替代设计。
您可以随时在方法名称上调用方法private
以使其成为私有:
>> class A >> def m >> puts 'hello' >> end >> end => nil >> a = A.new => # >> am hello => nil >> class A >> private :m >> end => A >> am NoMethodError: private method `m' called for # from (irb):227 from /usr/local/bin/irb19:12:in `'
或者,从课外:
A.send :private, :m
class A def test puts "test" end def test2 test end end a = A.new class << a private :test end a.test2 # works a.test # error: private method