Forum: Ruby attr_read, attr_writer, etc.

900885f72f544f27afa77c6e1758e43b?d=identicon&s=25 Frank Meyer (turing)
on 2007-08-13 16:29
Hello,
are these keywords or are they methods which create get/set methods for
the given attribute?

I suppose it's a mix of both, because I tried to write my own
attr_accessor but I  couldn't call it in the class definition, only on
an existing object.




Turing.
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2007-08-13 16:53
(Received via mailing list)
Alle lunedì 13 agosto 2007, Frank Meyer ha scritto:
>
> Turing.

They're instance method of the Module class. You can write them, if you
want:

class Module

  def my_attr_reader *args
    args.each do |a|
      define_method(a) do
        puts 'this method was generated by my_attr_reader';
        instance_variable_get("@#{a}")
      end
    end
  end

end

class C
  my_attr_reader :x

  def initialize x
    @x = x
  end
end

res = C.new(2).x
=> this method was generated by my_attr_reader
puts res
=> 2

Defining my_attr_reader in class Module will make it availlable in all
classes
and modules. You can define it in class Class to make it availlable only
in
classes, or you can define them in a single class. In this case,
however, it
should be defined as a class method, not as an instance method:

class MyClass
  def self.my_attr_reader
  ...

I hope this helps

Stefano
900885f72f544f27afa77c6e1758e43b?d=identicon&s=25 Frank Meyer (turing)
on 2007-08-13 20:03
Thanks for your explanation, but how would you write a attr_writer
method?
I don't know how I can pass a parameter list to define_method.



Turing.
F53b05cdbdf561cfe141f69b421244f3?d=identicon&s=25 unknown (Guest)
on 2007-08-13 21:07
(Received via mailing list)
Hi --

On Tue, 14 Aug 2007, Frank Meyer wrote:

> Thanks for your explanation, but how would you write a attr_writer
> method?
> I don't know how I can pass a parameter list to define_method.

Give the block a parameter:

   def my_attr_writer(*names)
     names.each do |name|
       define_method("#{name}=") {|x| instance_variable_set("@#{name}",
x) }
     end
   end


David
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.