這似乎並不工作:如何動態地將方法定義爲私有方法?
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 }
或者,剛剛從Test
類中運行
private :private_method
。
Module#private
有一個可選參數的方法名稱:
class Test
private :private_method
end
以上當然是等價的,以
Test.private :private_method # doesn't work
除了Module#private
是私有的,所以你必須使用反射來規避訪問限制:
Test.send :private, :private_method
不需要eval
。
似乎開始使用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!
(我意識到這是一個老問題,但我通過谷歌發生了跨越它。)
這很簡單,謝謝! :d – knoopx 2010-09-23 20:09:11