Version 1: The constructor creates two instance variables, @name
and @age
. These two variables are private (as are all Ruby instance variables), so you can't access them outside of the class.
Version 2: Exact same thing as #1 except that you're also defining a getter and setter method for the two variables. What attr_accessor
does is create two methods for each parameter that allow you to get/set the value of the instance variable with the same name.
Version 3: Exact same as #2 except that in your constructor you're not setting the instance variables directly, instead you're calling the User#name=
and User#age=
methods to set the value of your instance variables instead of setting them directly.
To clarify the difference between setting the instance variable directly and calling a setter method, consider this example:
user = User.new "Rob", 26
user.name = "Joe"
Here you are not actually setting the @name
variable of user
directly, instead you are calling a method called name=
on user
which sets the value of @name
for you. When you did the call to attr_accessor
in versions #2 and #3, it defined that method for you. However in version #1 you did not call attr_accessor
, so the example above would be invalid since there is no name=
method.