From: Stefano Crocco Date: 2007-03-04T04:47:31+09:00 Subject: Re: attr_reader explained 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.var_defined? => nil > class C > def initialize > @var=nil > end > end => nil > c1=C.new => # > 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