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?
The keyword self in Ruby enables you to access to the current object — the object that is receiving the current message. The word self can be used in the definition of a class method to tell Ruby that the method is for the self, which is in this case the class.
What is self? There's always a self object at any point in the Ruby code. Outside of any class/module/method definitions, self is a main object of the class Object . >> puts self, self.class main Object. Inside a method within a class, self is the object of that class.
self is a special variable that points to the object that "owns" the currently executing code. Ruby uses self everwhere: For instance variables: @myvar. For method and constant lookup. When defining methods, classes and modules.
To answer your question, you can use self to define your method as a class method inside your module, and without self to define the method as instance method and it depends on your need and usecase that when you want what type of behaviour from your module methods. Follow this answer to receive notifications.
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.
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.
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