Alle sabato 17 marzo 2007, Corey Konrad ha scritto:
> > c=C.new #now, C#initialize is called
> > c.instance_variables
> > => ["@var"] #now, @var exists
> > c.greater? 3
> > => false
> > c.greater? -1
> > => true
> >
> > By the way, if you define an initialize method for a class which doesn't
> > derive directly from Object, you'll usually want to call the parent
> > class's
> > initialize from your own, otherwise the parent class's instance
> > variables
> > won't be initialized:
> >
> > class A
> >  def initialize #We don't need to call Object#initialize: it does
> > nothing
> >   @var=0
> >  end
> > end
> >
> > class B < A
> >  def initialize
> >   super #We call the parent class's initialize; otherwise, @var won't be
> > set
> >   @var1=1
> >  end
> > end
> >
> > I hope this helps
> >
> > Stefano
>
> So i have to use the age accessor in an initialize method? i dont
> understand what the difference is between the age accessor in that
> example program and any of the others why would the age variable need to
> be set before i used it and what does that have to do with the error
> message i received telling me to parenthesize for future versions?
>
> thanks

First the last question. Your last code contained a syntax error:

puts "Now the size of the animal is #{animal.size)"

The last character before the ending quote should be a }, not a ). 


Regarding accessors and initialize: they're not related. The line

attr_accessor :var

is (more or less) simply a shortcut for this code:

def var
 @var
end

def var=value
 @var=value
end

In other words, attr_accessor is used to give access to instance variables to 
the world outside the instance itself. Initialize, on the other hand, is 
often used to set the instance variables to sensible values. If you don't set 
them explicitly, they'll be created and set to nil the first time they're 
used. Usually, this is bad. For instance, if the variable will contain a 
string, as in your example, sooner or later you'll want to call some string 
methods on it (such as sub or capitalize or downcase). If the instance 
variable hasn't been created before, it will be created now and set to nil, 
then the method will be called on it. But since nil doesn't have those 
methods, you'll get an error. Instead, if you set that variable to a string 
in initialize, you won't need to worry about that anymore.

To be simple: initialize is used to set the characteristics of an object at 
its birth. Accessors are used to change them later.

Stefano