0
我想寫一個基於所有方法的簡單回調函數,只需要添加一個單詞'hello'。我剛學過'別名',所以這個功能就是我想要嘗試的。我這裏還有代碼:如何使用alias_method回調所有Array方法?
a = []
class << a
Array.instance_methods(false).each do |meth|
alias_method :old_meth, meth
define_method(meth) do |*args, &block|
old_meth *args, &block
puts "hello"
end
end
end
a.push "good"
運行代碼時,我得到以下錯誤:
DRBServer.rb:6:in `pack': too few arguments (ArgumentError)
那麼我認爲這是因爲「包」的功能,所以我篩選「組」功能如下:
Array.instance_methods(false).each do |meth|
if meth != :pack
....
end
然後抱怨另一個功能 'drop_while' ......
DRBServer.rb:7:in `drop_while': wrong number of arguments(1 for 0) (ArgumentError)
我知道問題必須是傳遞參數(*參數,&塊)的方式,但如果我只是用這種方法將參數傳遞給一個方法,那麼它的工作原理是正確的。如下:
a = []
class << a
alias_method :old_push, :push
define_method("push") do |*args, &block|
old_push *args, &block
puts "hello"
end
end
a.push "good" => [output "hello"]
我真的很困惑,並感謝您的幫助。謝謝。
Thanks Mladen!我改變了你提到的代碼,它的工作原理。 – user1374460 2012-07-28 01:38:17