在没有实例化类的情况下调用ruby方法

Rim*_*ian 4 ruby ruby-on-rails class-method instance-methods

如果我在rails活动模型方法上调用一个方法,如下所示:

class Foo < ActiveRecord::Base

end

Foo.first
Run Code Online (Sandbox Code Playgroud)

我会回来第一个活跃的记录.我不必实例化该类.

但是,如果我创建自己的类并调用方法,我会得到一个例外:

class Person < ActiveRecord::Base
  def greeting
    'hello'
  end
end

Person.greeting 

#EXCEPTION: undefined method `greeting' for Person:Class
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题呢?

Ser*_*sev 13

有几种方法.最重要的两个是:实例方法和类实例方法.

Foo.first是一个类实例方法.它适用于类实例(Foo在本例中).如果它在类中存储了一些数据,那么该数据将在整个程序中全局共享(因为只有一个名为Foo的类(或者::Foo,确切地说)).

但是你的greeting方法是一个实例方法,它需要对象实例.例如,如果您的greeting方法将使用Person的名称,则它必须是实例方法,以便它能够使用实例数据(名称).如果它不使用任何特定于实例的状态,并且您真的认为它是类实例方法,那么使用self"前缀".

class Person < ActiveRecord::Base
  def self.greeting
    'hello'
  end
end
Run Code Online (Sandbox Code Playgroud)


Mat*_*ahé 8

尝试类方法:

class Person < ActiveRecord::Base
  def self.greeting
    'hello'
  end
end
Run Code Online (Sandbox Code Playgroud)

或者另一种语法:

class Person < ActiveRecord::Base
  class << self
    def greeting
      'hello'
    end
  end
end
Run Code Online (Sandbox Code Playgroud)