There's a time and place for metaprogramming. I think it gets mentioned heavily in Ruby books because people like to show off what Ruby can do that other languages can't do as well.
Metaprogramming is like not knowing the Japanese word for "burger" or "noodle soup", but knowing the Japanese for "this one please" ("kore o kudasai"), and being able to point at the item on the menu. It allows more flexibility, but you need more context to know exactly what is being done.
If you're creating ActiveRecord, which allows you to do find_by_foo
, then metaprogramming makes sense.
If you're writing a mutation testing library such as zombie-chaser, or a characterization testing application that tests different implementations of Ruby, such as the Small Eigen Collider, then metaprogramming makes sense.
However, if you're writing an application, then you generally shouldn't be metaprogramming, but merely programming. For example, if you're using instance_variable_set
in your application, that's more a code smell than an indication of how proficient you are.
Related questions you may want to read include https://stackoverflow.com/questions/1236191/what-will-i-learn-from-metaprogramming-ruby and Ruby metaprogramming online tutorial and Metaprogramming how much is too much? .
I really recommend the book "Metaprogramming Ruby", because it doesn't just teach you metaprogramming, but how Ruby works.
attr_accessor
example, as it shows important benefit of strong metaprogramming capabilities: metaprogramming keeps the language itself simple.attr_accessor
could easily be a separate language construct in another language (related: properties in C# etc.). In Ruby, it is merely another method. – Safekeeping