I was reading an article on meta-programming and it showed that you can define a method within another method. This is something that I had known for a while, but it made me ask myself the question: does this have any practical application? Is there any real life uses of defining a method within a method?
Ex:
def outer_method
def inner_method
# ...
end
# ...
end
My favorite metaprogramming example like this is dynamically building a method that you’re then going to use in a loop. For example, I have a query-engine I wrote in Ruby, and one of its operations is filtering. There are a bunch of different forms of filters (substring, equals, <=, >=, intersections, etc.). The naive approach is like this:
But if your working sets can get large, you’re doing this big case statement 1000s or 1000000s of times for each operation even though it’s going to take the same branch on every iteration. In my case the logic is much more involved than just a case statement, so the overhead is even worse. Instead, you can do it like this:
Now the one-time branching is done once, up front, and the resulting single-purpose function is the one used in the inner loop.
In fact, my real example does three levels of this, as there are variations in the interpretation of both the working set and the filter value, not just the form of the actual test. So I build an item-prep function and a filter-value-prep function, and then build a do_filter function that uses those.
(And I actually use lambdas, not defs.)