在不实例化类的情况下调用ruby方法 [英] Calling ruby method without instantiating class
问题描述
如果我像这样在rails活动模型方法上调用方法:
If I call a method on a rails active model method like so:
class Foo < ActiveRecord::Base
end
Foo.first
我将取回第一条活动记录.我不必实例化课程.
I'll get back the first active record. I don't have to instantiate the class.
但是,如果我创建自己的类并调用方法,则会出现异常:
But if I create my own class and call a method, I get an exception:
class Person < ActiveRecord::Base
def greeting
'hello'
end
end
Person.greeting
#EXCEPTION: undefined method `greeting' for Person:Class
如何解决该问题?
推荐答案
有几种方法.最重要的两个是:实例方法和类实例方法.
There are several kinds of methods. The two most important ones are: instance methods and class instance methods.
Foo.first
是一个类实例方法.它适用于类实例(在这种情况下为Foo
).如果它在类中存储了一些数据,那么这些数据将在您的程序中全局共享(因为只有一个名为Foo的类(确切地说是::Foo
)).
Foo.first
is a class instance method. It works on a class instance (Foo
, in this case). If it stores some data inside the class, that data is shared globally across your program (because there's only one class with name Foo (or ::Foo
, to be exact)).
但是您的greeting
方法是一个实例方法,它需要对象实例.例如,如果您的问候语方法将使用Person的名称,则它必须是实例方法,以便它能够使用实例数据(名称).如果它不使用任何特定于实例的状态,而您确实是将其用作类实例方法,则使用self
"prefix".
But your greeting
method is an instance method, it requires object instance. If your greeting method will use Person's name, for example, it has to be instance method, so that it will be able to use instance data (the name). If it doesn't use any instance-specific state and you really meant it to be a class instance method, then use the self
"prefix".
class Person < ActiveRecord::Base
def self.greeting
'hello'
end
end
这篇关于在不实例化类的情况下调用ruby方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!