Using self in Ruby
Posted on 12 February 2008 by Robin FisherOne of the things that had me confused early on when programming in Ruby was when to use “self” for a method and when not to.
The easiest way to summarise, I think, is to say that
self.methodshould be used when referring to a method that operates on the class itself.
methodshould be used when referring to a method that operates on an instance of the class.
The most common place this is seen in Rails application is in authentication systems. The method for logging a user into an application is usually written as:
Class User < ActiveRecord::Base
def self.authenticate(user, password) … endend
This is then called in the controller as:
Class SessionsController < ActionController::Base
def new @user = User.authenticate(params[:session]) endend
In contrast, methods can then be called on the @user object once the user has logged in. For example, to check if the user is an administrator, the following method could be used in our User class:
def is_admin?
…
end
This could then be called within the view, perhaps to display certain restricted information:
<%= if @user.is_admin? %>
As a complete aside, I love how the above code demonstrates the readability of Ruby. There is no doubt as to what that statement means.