Eliminating redundancy
One of the best reasons to use metaprogramming is to eliminate redundancy. No Ruby programmer wants to write the same or similar code over and over, after all, unless they are getting paid by the line. Imagine programming in Ruby without attr_accessor
, as shown in the following example:
class Foo def bar @bar end def bar=(v) @bar = v end def baz @baz end def baz=(v) @baz = v end end
It would definitely suck to have to define accessor methods this verbosely. It's hard to believe, but there are programming languages where you still have to do that, even some that were originally released after Ruby. Ruby realizes that no programmer likes that sort of repetitive coding, and being designed around programmer happiness, Ruby includes attr_accessor
and similar methods...