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.
class Main < Sinatra::Base
@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,""
self.create_user(params goes here)
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
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.