Understanding different ways of metaprogramming methods
There are two separate approaches to metaprogramming in Ruby. The two separate approaches each have advantages and disadvantages, so the most appropriate one to use depends on the specific situation.
So far in this chapter, you've seen examples of using define_method
, which is one of the methods used in block-based metaprogramming. There are other block-based metaprogramming methods, such as Class.new
, Module.new
, and Kernel#define_singleton_method
:
Class.new do # class-level block metaprogramming end Module.new do # module-level block metaprogramming end define_singleton_method(:method) do # singleton-method defining block metaprogramming end
Using these block-based metaprogramming methods is the recommended approach in most cases. The main flexibility advantage of using the block-based metaprogramming approach is that you can easily operate with external data and even external...