Search code examples
rubyinitializationattr-accessor

Why must I initialize variables in a class?


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.


Solution

  • 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.