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
About these ads

One thought on “Learning Ruby reimplementing it: attr_writer

  1. Thanks for the post! I got a wrong number of arguments exception when I tried to add more than one attribute like this:

    attribute_writer :one, :two

    I modified attribute_writer to take an arbitrary number of arguments:

    def attribute_writer(attr1, *rest)
    rest << attr1
    rest.each do |attribute|
    define_method("#{attribute}=".to_sym) do |value|
    instance_variable_set("@#{attribute}", value)
    end
    end
    end

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