예. 객체가 메시지에 응답하지 않으면, 루비는 수신기에 메시지 선택과 method_missing
메시지와 인수를 보낼 것입니다 : 당신이 method_missing
를 정의하면, 당신은 또한 그에 따라 respond_to_missing?
을 정의해야
class X
def method_missing(selector, *args, &blk)
puts "The message was #{selector.inspect}."
puts "The arguments were #{args.map(&:inspect).join(', ')}."
puts "And there was #{blk ? 'a' : 'no'} block."
super
end
end
x = X.new
x.some_method('some args', :some_other_args, 42)
# The message was :some_method.
# The arguments were "some args", :some_other_args, 42.
# And there was no block.
# NoMethodError: undefined method `some_method'
x.some_other_method do end
# The message was :some_other_method.
# The arguments were .
# And there was a block.
# NoMethodError: undefined method `some_other_method'
참고. 그렇지 않으면이 같은 이상한 행동을 얻을 다음과 같이이 특정 경우
x.respond_to?(:foo) # => false
x.foo # Works. Huh?
을, 우리가 모든 메시지를 처리, 그러므로 우리는 간단하게 정의 할 수 있습니다 :
class X; def respond_to_missing?(*) true end end
x.respond_to?(:foo) # => true
-1 즉, 전혀 관계가없는 일입니다. 질문을 다시 읽으십시오. – delnan
아, 내 잘못 .. 질문을 잘못 읽고 .. :( – RameshVel