Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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


This 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.


not 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


Fair 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.


Isn'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


Isn't that just syntactic sugar[1]?

Actually, it's runtime-during-parsing magic, IIRC.


You can.


This 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.


I'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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: