在类中调用类方法 [英] Calling a class method within a class
本文介绍了在类中调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我意识到这可能是一个幼稚的问题,但我仍然无法弄清楚如何在 Ruby 类中从另一个方法调用一个方法.
I realize this perhaps a naive question but still I cant figure out how to call one method from another in a Ruby class.
即在 Ruby 中可以执行以下操作:
i.e. In Ruby is it possible to do the following:
class A
def met1
end
def met2
met1 #call to previously defined method1
end
end
谢谢,
RM
推荐答案
那些不是类方法,它们是实例方法.您可以在示例中使用该类的实例从met2 调用met1 没有问题:
Those aren't class methods, they are instance methods. You can call met1 from met2 in your example without a problem using an instance of the class:
class A
def met1
puts "In met1"
end
def met2
met1
end
end
var1 = A.new
var1.met2
以下是使用类方法的等效方法,您通过在方法名称前加上类名来创建这些方法:
Here is the equivalent using class methods which you create by prefixing the name of the method with its class name:
class A
def A.met1
puts "In met1"
end
def A.met2
met1
end
end
A.met2
这篇关于在类中调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文