如何以及为什么我应该避免使用" self"在Ruby方法声明中

时间:2016-07-25 03:31:31

标签: ruby static self

我想知道是否有一种最简单的方法可以摆脱" self"从另一个类调用函数时。 例如,我这里有一个具有函数的类。

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

使用此我需要声明self.create_user(params goes here) 有没有办法摆脱自我?

提前致谢。

1 个答案:

答案 0 :(得分:1)

使用self没有任何问题,但它绕过了创建对象的变量实例的要求,因此一些顽固的OO程序员会建议避免使用self。如果你避免使用“self”,那么你就不得不初始化你的类并将它分配给一个变量名,这会迫使你把它想象成一个真正的对象,而不仅仅是一组函数。

这是一个示例类,用于演示如何使用和不使用“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!

是否在声明中使用self应该取决于您希望方法使用的数据。如果方法对作为参数传递的变量进行操作,则使用“self”。另一方面,如果您希望它们充当真正的对象方法,请不要使用“self”。 “True”对象方法可以对您创建的对象中的类变量(字段)的状态进行操作,并将其分配给一个或多个变量名。