Version 1: The constructor creates two instance variables, @name and @age . These two variables are private (like all Ruby instance variables), so you cannot access them outside the class.
Version 2: Same as # 1, except that you also define getter and setter for two variables. What attr_accessor does creates two methods for each parameter that allow you to get / set the value of an instance variable with the same name.
Version 3: Same as # 2, except that you do not set instance variables directly in your constructor; instead, you call 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 the setter method, consider this example:
user = User.new "Rob", 26 user.name = "Joe"
Here you are not actually setting the @name user variable directly, instead you are calling a method called name= on user , which sets @name for you. When you made the attr_accessor call in versions # 2 and # 3, he defined this method for you. However, in version # 1 you did not call attr_accessor , so the above example is not valid because there is no name= method.
robbrit
source share