在Ruby中,消息是字符串。如何定义如何将任意字符串响应为消息,而不是预先定义一组消息及其响应?
发布于 2013-10-30 16:44:54
class MessageResponder
def method_missing(method, *args, &block)
"You called #{method}(#{args.map(&:inspect).join(', ')})#{' with block' if block}"
end
end
responder = MessageResponder.new
responder.foo(3, 7)
# => You called foo(3, 7)
如果消息不对应于任何类方法,则调用名为method_missing
的方法。你可以在这个例子中看到它收到了什么。如果您覆盖它,您可以响应任何消息。
发布于 2013-10-30 16:43:02
没有匹配方法的消息被发送到method_missing
。您可以实现它来响应您喜欢的任何内容。
https://stackoverflow.com/questions/19696438
复制