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

Joh*_*rte 1 ruby static 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
Run Code Online (Sandbox Code Playgroud)

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

提前致谢。

eme*_*ery 5

使用 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
Run Code Online (Sandbox Code Playgroud)

输出:

Hello, static class method world!
Hello, object-oriented world!
Run Code Online (Sandbox Code Playgroud)

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