XPlayer

A blog on my daily efforts to be a better developer, and keep improving every day.

Learning Ruby Reimplementing It: Attr_writer

| Comments

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

Comments