John Geliberte John Geliberte - 4 months ago 7
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
begin
if password == confirm_pass
@creation_flag = User.create(username: username,password: password,full_name: fullname).valid?
end
rescue Exception => e
puts 'Error Occured: '+e.message,""
end
return @creation_flag
end

def self.

end
end


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

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!'
  end

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

end

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

# You must create an object instance variable to call methods without 'self'
object = StaticVersusObjectMethod.new
object.object_method

output:

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.