Possible Duplicate:
Why do Ruby setters need “self.” qualification within the class?
Can someone explain the difference between the following, and why it isn't as one might 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 are assigning, you have to use the self
keyword. Why can't you use this in an initialize
method? Or can you? I tried using it and it didn't seem to work as expected, I'm just confused as to which technique to use and when and more importantly why.
I really hope someone can clear this up for me once and for all :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With