Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To use self. or not.. in Rails

I've been coding in Ruby for sometime now, but I don't understand when to use:

def self.METHOD_NAME end 

or just:

def METHOD_NAME end 

In any Rails model. Is "self" a modifier like private in Java? When should I use it and when not?. Thanks a ton.

like image 233
Swamy g Avatar asked Dec 22 '08 12:12

Swamy g


People also ask

What is the use of self in rails?

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.

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 self refer to in an instance method body?

the method self refers to the object it belongs to. Class definitions are objects too. If you use self inside class definition it refers to the object of class definition (to the class) if you call it inside class method it refers to the class again.


2 Answers

def self.method_name end 

defines a class method.

def method_name end 

defines an instance method.

This is a pretty good post on it.

like image 51
DanSingerman Avatar answered Oct 05 '22 09:10

DanSingerman


A quick explanation of what that means:

In ruby, you can define methods on a particular object:

a = "hello"  def a.informal   "hi" end  a.informal => "hi" 

What happens when you do that is that the object a, which is of class String, gets its class changed to a "ghost" class, aka metaclass, singleton class or eigenclass. That new class superclass is String.

Also, inside class definitions, self is set to the class being defined, so

class Greeting   def self.say_hello     "Hello"   end   #is the same as:   def Greeting.informal     "hi"   end end 

What happens there is that the object Greeting, which is of class Class, gets a new metaclass with the new methods, so when you call

Greeting.informal => "hi" 

There's no such thing as class methods in ruby, but the semantics are similar.

like image 37
krusty.ar Avatar answered Oct 05 '22 09:10

krusty.ar