What is metaprogramming in Ruby/Rails and give examples?

Answer

Metaprogramming is writing code that writes or modifies code at runtime. Ruby's dynamic nature makes it powerful for metaprogramming. Key techniques: define_method(:foo) { ... } — defines a method dynamically; method_missing — called for undefined methods, used to implement dynamic finders; send(:method_name) — calls any method by name including private; class_eval / module_eval — opens a class to add methods at runtime; attr_accessor is itself a macro that calls define_method. Rails uses metaprogramming extensively — ActiveRecord's associations (has_many), validations (validates), and callbacks are all macros implemented via metaprogramming.