Wednesday, March 25, 2009

attr_accessor is a method

Somehow I thought the action of defining a class is an declaration and doesn't execute statements, but I was wrong.
class MyClass
  put "Hello world"
  def MyMethod
    puts "output from MyMethod"
  end
end
The Ruby code above actually spits "Hello world". I tried this with Python and Python did the same. The reason I wondered this was Ruby's attr_accessor.
class MyClass
  attr_accessor :a
end
It looked to me like an declaration of @a to have accessors, but it isn't. attr_accessor is an method implemented in Module class and it is not a reserved word. The truth is that attr_accessor is executed when the source code is interpreted and it defines accessor methods. AH!

No comments: