Learning Ruby reimplementing it: attr_reader

How handy is the attr_reader method? Very handy indeed.

Never asked yourself how it may be implemented? Just do it!

This is my take:

module Kernel
  def attribute_reader(attribute)
    define_method(attribute) do
      instance_variable_get("@#{attribute}")
    end
  end
end


class MyClass
  attribute_reader :my_attribute
end

m = MyClass.new
m.instance_variable_set("@my_attribute", 42)

puts m.my_attribute # => 42

What’s yours?

Have fun!