这似乎不起作用:
class Test
private
define_method :private_method do
"uh!"
end
end
puts Test.new.private_method
这似乎不起作用:
class Test
private
define_method :private_method do
"uh!"
end
end
puts Test.new.private_method
Test.instance_eval { private :private_method }
或者,只是运行
private :private_method
从Test
班内。
似乎从 Ruby 2.1 开始,define_method
尊重private
:
$ rvm 2.1.0
$ ruby /tmp/test.rb
/tmp/test.rb:10:in `<main>': private method `private_method' called for #<Test:0x00000102014598> (NoMethodError)
$ rvm 2.0
$ ruby /tmp/test.rb
uh!
(我意识到这是一个老问题,但我是通过谷歌偶然发现的。)
Module#private
采用方法名称的可选参数:
class Test
private :private_method
end
以上当然等价于
Test.private :private_method # doesn't work
除了Module#private
是私有的,所以你必须使用反射来规避访问限制:
Test.send :private, :private_method
没有eval
必要。