是的。如果一個對象不回覆短信,紅寶石將發送method_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'
請注意,如果你定義method_missing
,你也應該定義respond_to_missing?
相應。否則,你得到奇怪的行爲是這樣的:
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 2011-03-11 13:46:32
啊,我的壞..誤讀了這個問題.. :( – RameshVel 2011-03-11 14:02:42