Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`respond_to?` vs. `respond_to_missing?`

What is the point of defining respond_to_missing? as opposed to defining respond_to?? What goes wrong if you redefine respond_to? for some class?

like image 276
sawa Avatar asked Dec 09 '12 23:12

sawa


People also ask

What is Respond_to in Ruby?

respond_to? is a Ruby method for detecting whether the class has a particular method on it. For example, @user.respond_to?('eat_food')

What is Method_missing in Ruby?

What is method_missing? method_missing is a method that ruby gives you access inside of your objects a way to handle situations when you call a method that doesn't exist. It's sort of like a Begin/Rescue, but for method calls. It gives you one last chance to deal with that method call before an exception is raised.


1 Answers

Without respond_to_missing? defined, trying to get the method via method will fail:

class Foo   def method_missing name, *args     p args   end    def respond_to? name, include_private = false     true   end end  f = Foo.new f.bar  #=> [] f.respond_to? :bar  #=> true f.method :bar  # NameError: undefined method `bar' for class `Foo'  class Foo   def respond_to? *args; super; end  # “Reverting” previous redefinition    def respond_to_missing? *args     true   end end  f.method :bar  #=> #<Method: Foo#bar> 

Marc-André (a Ruby core committer) has a good blog post on respond_to_missing?.

like image 85
Andrew Marshall Avatar answered Sep 24 '22 19:09

Andrew Marshall