attr_writer vs attr_accessor

Y

ycsunil

Hello all,

From readings I understood that attr_accessor is the one which has the
property of attr_reader and attr_writer. If we define a variable as
attr_writer, we can use it to read and write as well. My question is;
why do we need to use attr_accessor since attr_writer does the job of
read and write?

-Sunil
 
T

Thomas Wieczorek

Hello all,

From readings I understood that attr_accessor is the one which has the
property of attr_reader and attr_writer. If we define a variable as
attr_writer, we can use it to read and write as well. My question is;
why do we need to use attr_accessor since attr_writer does the job of
read and write?

Did you try it? I get an error, when I use the following

irb(main):001:0> class Foo
irb(main):002:1> attr_writer :bar
irb(main):003:1> def initialize
irb(main):004:2> @bar = "hallo"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> Foo.new.bar
NoMethodError: undefined method `bar' for #<Foo:0x2ad5640 @bar="hallo">
from (irb):7
irb(main):008:0>

attr_writer just creates the bar=(value) method, no bar() method to
access the attribute.
 
Y

ycsunil

Did you try it? I get an error, when I use the following

irb(main):001:0> class Foo
irb(main):002:1> attr_writer :bar
irb(main):003:1> def initialize
irb(main):004:2> @bar = "hallo"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> Foo.new.bar
NoMethodError: undefined method `bar' for #<Foo:0x2ad5640 @bar="hallo">
        from (irb):7
irb(main):008:0>

attr_writer just creates the bar=(value) method, no bar() method to
access the attribute.

Thanks! for clearing the doubt with an example. In general I thought;
if varialbe can be writable then it should hold property of
readable... which is not true in attr_writer.
 
J

Jesús Gabriel y Galán

Thanks! for clearing the doubt with an example. In general I thought;
if varialbe can be writable then it should hold property of
readable... which is not true in attr_writer.

attr_xxx do not "declare" any property or type of property.
They just generate methods.
attr_reader :xxx generates a method that returns the value of the
instance variable @xxx
attr_writer :xxx generates a method xxx= that sets the value of the
instance variable @xxx
attr_accessor :xxx generates the two above methods.

Hope this helps,

Jesus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top