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 :)