모든 메소드에 기반한 간단한 콜백 함수를 작성하고 싶습니다. 그냥 '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)
,
나는 매개 변수 (* args, & 블록)를 전달하는 방법으로 문제가 있어야한다는 것을 알고있다. 그러나이 방법을 사용하여 하나의 메서드에 매개 변수를 전달하면 문제가 해결된다. 다음과 같이 :
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"]
저는 정말 혼란스럽고 도움을 주셔서 감사합니다. 감사.
감사합니다. Mladen! 내가 말한대로 코드를 변경하고 작동합니다. – user1374460