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 used
@lines = lines
Mostly I see people using @ in initialize method. Is there a preferred way of doing among these two and why?
When you use
@lines, you are accessing the instance variable itself.self.linesactually goes through thelinesmethod of the class; likewise,self.lines = xgoes through thelines=method. So use@when you want to access the variable directly, andself.when you want to access via the method.To directly answer your question, normally you want to set the instance variables directly in your
initializemethod, but it depends on your use-case.