如何将方法动态定义为私有?

这似乎不起作用:

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 `
': private method `private_method' called for # (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是私有的,因此您必须使用reflection来规避访问限制:

 Test.send :private, :private_method 

没有必要的eval