Understanding Ruby Class Instance Variables

Possible duplicate:
Why do I need Ruby settings to be me. classroom qualifications?

Can someone explain the difference between the following and why this is not as one would expect:

# version #1 class User def initialize(name, age) @name = name @age = age end end #version #2 class User attr_accessor :name, :age def initialize(name, age) @name = name @age = age end end #version #3 class User attr_accessor :name, :age def initialize(name, age) self.name = name self.age = age end end 

From what I understood, in methods, when you assign, you should use the self keyword. Why can't you use this in the initialize method? Or you can? I tried to use it, and it did not work as expected, I'm just confused about what technique to use and when and more importantly why.

I really hope someone can figure it out once and for all :)

+8
ruby
source share
2 answers

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.

+15
source share

You do not need to use self in a method; for an instance variable you should assign directly using @, as in version 1 or 2. The self is not like Python; it is used, for example, to declare a class method (for example, a static function in C ++).

0
source share

All Articles