How to make your own *attr_accessor* method

This evening I wondered how I could create my own attr_accessor method, and here's what I came up with:

class Base

  def initialize()
    @h = {}
  end

  def self.attr2_accessor(*attributes)

    attributes.each do |attribute|

      class_eval do

        define_method attribute { @h[attribute] }

        define_method (attribute.to_s + '=').to_sym do |val|
          @h[attribute] = val
        end

      end
    end
  end

end

class Fun < Base
  attr2_accessor :colour
end

fun = Fun.new
fun.colour = 'brown'
fun.colour #=> brown

Resources