Ruby's Attribute Accessors

Nola Stowe wrote an article about attribute getters and setters recently, with comparsion between PHP and Ruby. Referring to Ruby's attr_reader and attr_writer, she said:

And, I like have getVAR setVAR. The ruby shortcuts don't allow that.

The beauty of Ruby is that you can customize the classes very easily:

class GetAndSet
  def self.attr_getter(*symbols)
    symbols.each do |symbol|
      define_method(("get" + symbol.id2name).to_sym, instance_method(symbol))

  attr_getter :foo


blah =
blah.getfoo # "Return foo"

The above code creates a attr_getter method that works the same way as attr_reader, except that whatever you define automatically gets an accessor function of getXXX like desired. You can create a setter in much the same way.

Guess I shouldn't say RoR can't do [...]

but just find a way to do it! :) Thanks