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!

One thought on “Learning Ruby reimplementing it: attr_reader

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s