method missing

suggest change

Parameters

Parameter Details
method The name of the method that was called, as a symbol. In the example below, :say_moo.
*args The arguments passed to that call. There may be any number, including none.
&block The block passed to the call, either do ... end or { ... }.

Remarks

Call super at the end of method_missing. Otherwise a call you do not handle returns nil instead of raising NoMethodError.

For example, this method_missing is going to cause problems:

class Animal
  def method_missing(method, *args, &block)
    say, speak = method.to_s.split("_")
    if say == "say"
      speak
    end
  end
end

# => Animal.new.foobar
# => nil # This should really be raising an error

method_missing is a good tool to use when appropriate, but has two costs you should consider. First, method_missing is less efficient. Ruby searches the class and its ancestors before it falls back to this method. That cost can be small in a simple case and can still add up. Second, this is metaprogramming: the implementation has to handle unexpected input safely.

You should also override respond_to_missing? like so:

class Animal
  def respond_to_missing?(method, include_private = false)
    method.to_s.start_with?("say_") || super
  end
end

# => Animal.new.respond_to?(:say_moo) # => true

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents