John Geliberte John Geliberte - 1 year ago 53
Ruby Question

How and why should I avoid using "self" in a Ruby method declaration

I was wondering if there is a simplest way to get rid of the "self" when calling a function from another class.
Example, I have here a class that has a function.

module Portfolio
class Main < Sinatra::Base

def self.create_user(username,password,confirm_pass,fullname)
@creation_flag = false
if password == confirm_pass
@creation_flag = User.create(username: username,password: password,full_name: fullname).valid?
rescue Exception => e
puts 'Error Occured: '+e.message,""
return @creation_flag

def self.


to use this i need to declare
self.create_user(params goes here)

is there a way to get rid of the self?.

Thanks in advance.

Answer Source

There's nothing wrong with using self, but it bypasses the requirement to create a variable instance of your object, so some die-hard OO programmers would suggest avoiding self for that reason. If you avoid "self" then you are forced to initialize your class as a variable, which forces you think of it more as an object class, and not just a collection of functions.

Here's an example class to demonstrate how you would call methods with and without "self"

class StaticVersusObjectMethod

  def self.class_method
    puts 'Hello, static class method world!'

  def object_method
    puts 'Hello, object-oriented world!'


# No need to create an object instance variable if the method was defined with 'self'

# You must create an object instance variable to call methods without 'self'
object =


Hello, static class method world!
Hello, object-oriented world!

So, whether you use self should depend on the data you want your method to be able to use. It makes sense to declare your methods using self if the methods will only operate on the data you pass into the method parameters. On the other hand, don't use self if you want them to act as true object methods. "True" object methods without "self" can operate on the parameters passed in and also the state of the class variables (fields) in the objects themselves, which you can create and assign to a one or more variable names.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download