Here is my ruby code
class Demo
attr_accessor :lines
def initialize(lines)
self.lines = lines
end
end
In the above code I could have
When you use @lines
, you are accessing the instance variable itself. self.lines
actually goes through the lines
method of the class; likewise, self.lines = x
goes through the lines=
method. So use @
when you want to access the variable directly, and self.
when you want to access via the method.
To directly answer your question, normally you want to set the instance variables directly in your initialize
method, but it depends on your use-case.
The main difference would be if you redefined lines=
to do something other than @lines = lines
.
For example, you could add validation to the attribute (for example, raising if lines
is empty).
self.lines
is a method, @lines
is the instance variable. In your constructor you'll want to use self.lines I would argue, but that's up for debate. It's just a stylistic difference, really. If you want a deeper discussion of direct vs. indirect variable access, read the chapter from Kent Beck's Smalltalk Best Practice Patterns.
I think there is a little difference that has not be mentioned yet. The instance variable @lines can only be accessed within the class.
class Foo
def initialize
@lines = 1
end
end
foo = Foo.new
foo.lines
>> NoMethodError: undefined method `lines' for #<Foo:0x1017cfb80 @lines=0>
foo.send(:lines)
>> 1
If you define attr_accessor :lines all instances of that class can access the lines variable:
class Foo
attr_accessor :lines
def initialize
self.lines = 1
end
end
foo = Foo.new
foo.lines
>> 1
If you want your variable to be accessible for all instances you should use attr_accessor.