Alle sabato 17 marzo 2007, Corey Konrad ha scritto:
Michael Guterl wrote:
>> end
>> end
>>
>> animal = Animal.new
>
> ArgumentError: wrong number of arguments (0 for 2)
>
> Your Animal.new is expecting you to pass in color and size.
>
> animal = Animal.new("brown", "big")
>
> animal.color = "brown"
ah ok i understand that i am just learning all this OO stuff i just
thought i needed to use the initialize method but i dont even need to
create one for a default object state at all i can just do this as well
and the program worked fine,
class Animal
attr_accessor :color
attr_accessor :size
end
that is pretty cool i'm having a fun time learning this language
compared to something like vb.net.
Whenever you call the new method of a class, it calls the initialize method of
the instance it just created. If you didn't define an initialize method for
that class, the initialize method of the parent class will be called, or the
parent class's parent... and so on. Going on the class hyerarchy, we reach
Object#initialize, which (I think) does nothing.
If, as it often happens, you need instance variables, it's usually wise to
define an initialize method in order to set them to a sensible value (or to a
value passed by the caller using parameters). If you don't, the first time
you reference an instance variable, it will be created and set to nil, which
may not be what you want.
For example, take the following class
class C
def greater? number
@var > number
end
end
As you can see, this class defines an instance method which tells whether its
instance variable @var is greater than the given number or not.
Let's see what happens when we run this code:
c=C.new # Object#initialize is called.
c.instance_variables # No instance variables exist
=>
c.greater? 3
=>NoMethodError: undefined method `>' for nil:NilClass
We got an error, because @var is created on the spot and set to nil, and nil
doesn't have a > method.
If we add an initialize method, instead, we have:
class C
def initialize
@var=0
end
def greater? number
@var > number
end
end
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
···
> On 3/17/07, Corey Konrad <0011@hush.com> wrote: