From: Robert Klemme Date: 2012-09-01T21:02:57+09:00 Subject: Re: Constructor or a Method On Sat, Sep 1, 2012 at 1:59 PM, Rubyist Rohit wrote: >> Note that both the method definitions are useless here, as using >> attr_accessor >> already creates two methods doing exactly what your hand-written methods >> do. >> >> Stefano > > @Stefano; > > What if I use 'attr_reader' instead of 'attr_accessor'? You only get method #name and not also #name=. Btw, you can easily try these things out in IRB: irb(main):007:0> class Customer; attr_accessor :name; end => nil irb(main):008:0> c = Customer.new => # irb(main):009:0> c.name = "foo" => "foo" irb(main):010:0> c.name => "foo" irb(main):011:0> class C2; attr_reader :name; end => nil irb(main):012:0> c = C2.new => # irb(main):013:0> c.name = "foo" NoMethodError: undefined method `name=' for # from (irb):13 from /usr/local/bin/irb19:12:in `
' irb(main):014:0> c.name => nil Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/