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?
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.
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.
Did you try it? I get an error, when I use the following
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.
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.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.