Learning Ruby reimplementing it: attr_writer

This is how attr_writer may be (re)implemented:

module Kernel
  def attribute_writer(attribute)
    define_method("#{attribute}=".to_sym) do |value|
      instance_variable_set("@#{attribute}", value)
    end
  end
end

class MyClass
  attribute_writer :my_attribute
end

m = MyClass.new
m.my_attribute = 23

puts m.instance_variable_get "@my_attribute" # => 23
Advertisements

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!