Stefano Crocco
3/3/2007 7:48:00 PM
Alle sabato 3 marzo 2007, Raj Sahae ha scritto:
> attr_reader, in it's common usage, creates instance variables and
> defines a method by which you can read them.
Actually, attr_reader doesn't create the variable, just the accessor method.
To see this, do the following in irb:
> class C
> attr_reader :var
> def var_defined?
> defined?(@var)
> end
> end
=> nil
> c=C.new
=> #<C:0xb7a4c650>
> c.var_defined?
=> nil
> class C
> def initialize
> @var=nil
> end
> end
=> nil
> c1=C.new
=> #<C:0xb7cf1a04 @var=nil>
> c1.var_defined?
=> "instance-variable"
As you can see, in the first case (the variable called c) doesn't have the
@var instance variable defined. Even after you call the var method defined
using attr_reader, the variable is still not defined. To define it, you need
to explicitly assign it to a value (using @var= something inside an instance
method of the class or using instance_variable_set)
Stefano