面试题答案
一键面试method_missing
方法工作原理
在 Ruby 中,当调用一个对象的方法,而该对象并没有定义这个方法时,Ruby 会调用 method_missing
方法。method_missing
方法接受方法名作为符号,以及传递给该方法的参数。它提供了一种机制来处理未定义方法的调用,使得代码可以在运行时动态地生成响应。
简单动态方法派发示例
class DynamicMethodExample
def method_missing(method_name, *args, &block)
if method_name.to_s.start_with?('say_')
puts "You said: #{method_name.to_s.split('say_').last}"
else
super
end
end
end
example = DynamicMethodExample.new
example.say_hello
在上述示例中,当调用 example.say_hello
时,由于 DynamicMethodExample
类中没有定义 say_hello
方法,Ruby 会调用 method_missing
方法。method_missing
方法检查方法名是否以 say_
开头,如果是,则打印出相应的信息。如果方法名不符合条件,则调用 super
,这将触发默认的未定义方法错误处理。