I’m new to programming and am trying to figure out the purpose of “initialize” in creating a class.
Here’s an example:
class Person
def initialize(name)
@name = name
@pet = nil
@home = 'NYC'
end
end
So initializing is to create a bunch of attributes that I can pull out directly by saying Person.name and Person.pet and Person.home right? Is “initialize” just to compact a bunch of variables into one place? Would I accomplish the same thing doing this:
class Person
pet = nil
home = 'NYC'
#not so sure how to replicate the @name here.
end
Wouldn’t I be able to access the values with Person.pet and Person.home the same way as I would in the first code?
This is a little tricky in Ruby (as opposed to, say, Java) since both classes and instances of classes are actual objects at runtime. As such, a class has its own set of variables, and each instance of that class also gets its own set of variables (distinct from the class’s variables).
When you say
You’re setting a variable, pet, which is local only to the class object called
Person.The way to manipulate the variables of an instance of a class is to use the variables in methods:
Here, pet refers to a local variable of a given instance of
Person. Of course, this pet variable is pretty useless as defined, since it’s just a local variable that goes away after theinitializefunction completes. The way to make this variable persist for the lifetime of the instance is to make it an instance variable, which you accomplish by prefixing it with a@. And thus we arrive at your first initialize:So, as to why you need
initialize. Since the only way to set the instance variables of instances ofPersonis within methods ofPerson, this initialization needs to be in some method.initializeis just the convenient name for a method which is automatically called when your instance is first created.