On Sat, Sep 1, 2012 at 1:59 PM, Rubyist Rohit <[email protected]> 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
=> #<Customer:0x2029f5c0>
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
=> #<C2:0x202a2914>
irb(main):013:0> c.name = "foo"
NoMethodError: undefined method `name=' for #<C2:0x202a2914>
from (irb):13
from /usr/local/bin/irb19:12:in `<main>'
irb(main):014:0> c.name
=> nil
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en