14 Jan 2009, 12:01
N686048349_5726_pragsmall

Jamie Hunter Warnock (1 post)

No solution in code for my_attr_accessor example, so heres mine, also expanded module to take multiple arguments

module Accessor
  def my_attr_accessor(*names)
    names.each do |name|
      ivar_name = "@#{name}"
      define_method(name) do
        instance_variable_get(ivar_name)
      end
      define_method("#{name}=") do |value|
        STDERR.puts "ivar name = #{ivar_name}, ivar value = #{value}"
        instance_variable_set(ivar_name, value)
      end
    end
  end
end

class Kitten
  extend Accessor
  my_attr_accessor :paws, :meat, :hours_sleep
end

k = Kitten.new
k.paws = 4
k.meat = "chicken"
k.hours_sleep = 8
p k
  You must be logged in to comment