Why must I initialize variables in a class?

140 views Asked by At

I am in the process of learning the new Ruby language and am a little confused as to why all variables must be initialized.

I would think that the attr_accessor method would cover this. It seems redundant to do both. Does the attr_accessor not assume that the variable is global?

Any help in explaining this would be greatly appreciated.

2

There are 2 answers

2
BulletTime On BEST ANSWER

You don’t need to initialize anything.

If you think about the "initialize" method:

class People
attr_accessor :name,:age,:sex
  def initialize(name,age,sex)
    @name = name
    @sex = sex
    @age = age
   end
end

It's a construct you chose to do, when creating classes and organize your app. This method (initialize) will be executed when you call the new method for People: People.new.

attr_accessor gives you a setter and getter with meta-programing, meaning you don't need to type a lot of code.

Below is an example of a getter method, commonly known as a "reader", elegantly replaced with attr_reader:

def name
  @name = name
end

And the corresponding setter method, also known as a "writer" using attr_writer:

def name=(name)
  @name = name
end

Both setter and getter you can use with attr_accessor. Perhaps I digressed, but I wanted to explain the concept as I understood it since it seems you didn’t understand it well.

Short answer is, you don’t need to initialize anything if you don't want to.

0
Joseph On

Do you mean instance variables defined in a class?

If so, defining them in def initialize ensures that each object of the class is created with the appropriate variables.

attr_accessor can then be used to add read/write methods for each of the variables.

def initialize does not automatically add the read/write methods because not all variables should have them (e.g., an id would likely have a read method, but probably not a write method).