在不实例化类的情况下调用ruby方法
如果我在rails活动模型方法上调用方法,如下所示:
class Foo < ActiveRecord::Base end Foo.first
我会回到第一个活跃的记录。 我不必实例化该类。
但是如果我创建自己的类并调用方法,我会得到一个exception:
class Person < ActiveRecord::Base def greeting 'hello' end end Person.greeting #EXCEPTION: undefined method `greeting' for Person:Class
我怎么能让这个问题消失呢?
有几种方法。 最重要的两个是:实例方法和类实例方法。
Foo.first
是一个类实例方法。 它适用于类实例(在本例中为Foo
)。 如果它在类中存储了一些数据,那么这些数据将在整个程序中全局共享(因为只有一个名为Foo的类(或者说确切地说是::Foo
))。
但是你的greeting
方法是一个实例方法,它需要对象实例。 例如,如果您的greeting方法将使用Person的名称,则它必须是实例方法,以便它能够使用实例数据(名称)。 如果它不使用任何特定于实例的状态,并且你真的认为它是一个类实例方法,那么使用self
“前缀”。
class Person < ActiveRecord::Base def self.greeting 'hello' end end
尝试类方法:
class Person < ActiveRecord::Base def self.greeting 'hello' end end
或者另一种语法:
class Person < ActiveRecord::Base class << self def greeting 'hello' end end end
class Person < ActiveRecord::Base def Person.greeting 'hello' end end
也会工作。 我喜欢它,因为它很清楚它的作用; 但是,当您决定重命名Person类时,它将导致错误。
class Person < ActiveRecord::Base def self.greeting 'hello' end end
要做一个静态方法试试这个:
MyModel类 def self.do_something 把“这是一种静态方法” 结束 结束 MyModel.do_something#=>“这是一个静态方法” MyModel :: do_something#=>“这是一个静态方法”