5 ms·
Ruby's attr_accessor is a great example of this. When you add the line attr_accessor :age a bit of nifty metaprogramming kicks in and generates the follow
by cubicle67 14y ago
Ruby's attr_accessor is a great example of this. When you add the line
attr_accessor :age
a bit of nifty metaprogramming kicks in and generates the following getter/setter methods in your class
def age= value
@age = value
end
def age
@age
end
- SagelyGuru 14y agoThis is not what I would call real code, or what the questioner was after, I feel. It is just mandatory syntactical verbiage to appease the idol of objective programming.
- cubicle67 14y agonot sure what makes code "real" or not to you, but I used this as a very simple example of "code that writes code" that probably all Ruby users have used, possibly without thinking about what it's doing and yes, pretty much all code we write is mandatory syntactical verbiage
- SagelyGuru 14y agoFair enough. I should be more precise. I don't think automatic programming is (or should be) just about syntactical translations. Just as nowadays we smile about the fact that the first Fortran compiler was considered to be AI.
- JeanPierre 14y agoIsn't that just syntactic sugar[1]? I cannot see any kind of metaprogramming going on here - unless you can define attr_accessor and similar parts yourself. [1] http://en.wikipedia.org/wiki/Syntactic_sugar http://en.wikipedia.org/wiki/Syntactic_sugar
- philwelch 14y agoYou can.
- stcredzero 14y agoIsn't that just syntactic sugar[1]? Actually, it's runtime-during-parsing magic, IIRC.
- FuzzyDunlop 14y agoThis is pretty much the same as @synthesize in Objective-C. I think a better example of metaprogramming might be the usage of method_missing in Ruby, or, say, __call and __callStatic in PHP, which all allow one to do interesting things with non-existent method invocations.
- cubicle67 14y agoI'd argue that method_missing isn't metaprogramming at all. What about ActiveRecord (Rails' default ORM)? That makes great use of code-writing-code to generate a ton of methods on your class all based on db fields.