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.
You don’t need to initialize anything.
If you think about the "initialize" method:
It's a construct you chose to do, when creating classes and organize your app. This method (
initialize
) will be executed when you call thenew
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
:And the corresponding setter method, also known as a "writer" using
attr_writer
: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.