Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby should I use self. or @

Tags:

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?

like image 856
Nick Vanderbilt Avatar asked Mar 11 '11 16:03

Nick Vanderbilt


People also ask

Why do we use self in Ruby?

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 does class << self mean Ruby?

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.

What does self mean in Ruby?

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.

What is self in a Ruby module?

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.


2 Answers

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.

like image 192
mipadi Avatar answered Sep 28 '22 04:09

mipadi


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.

like image 44
eggie5 Avatar answered Sep 28 '22 05:09

eggie5