`method_missing` call stack in Ruby
November 23rd, 2010 Posted in Programming, RubyJust found out something cool from reading “Don’t Know Metaprogramming In Ruby?” from RubyLearning blog. Consider this code snippet:
class Person end class Student < Person end class HighSchoolStudent < Student end
If you’re calling some method that’s undefined, let’s say we’re calling HighSchoolStudent#name Ruby will try to call the method in this order:
- HighSchoolStudent#name
- Student#name
- Person#name
- Object#name
- Kernel#name
- BasicObject#name
- HighSchoolStudent#method_missing
- Student#method_missing
- Person#method_missing
- Object#method_missing
- Kernel#method_missing
- BasicObject#method_missing
From this example, you can see that not explicitly define method and capture it in method_missing might not be good in terms of the performance. So, what should you do?
I think the best way to do it, if you know that this method will get called again, would be define the ‘real’ method after it gets called. That will reduce the call stack starting from the second run, resulting in faster code.
# Let say we're defining method for #*_with_id here def method_missing(name, *args) super if name !~ /_with_id$/ define_method "#{name}_with_id" do instance_variable_get(:id) + "-" + instance_variable_get(:name) end end
Hope this will make your code run faster, while still DRY.


