rails不同的方式定义方法
问题描述:
我一直在研究Rails的时间不长,直到现在....所以如果有随时纠正我rails不同的方式定义方法
我看到有两种方式在导轨
def method_name(param)
def self.method_name(param)
的差限定的方法(如我明白)是1主要用于在控制器而2中使用模型...但偶尔我碰到模型的方法,像'1的定义。
你能向我解释两种方法的主要区别吗?
答
Number 1.这定义了一个instance method
,它可以在模型的实例中使用。
Number 2.这定义了一个class method
,只能由该类自己使用。
实施例:
class Lol
def instance_method
end
def self.class_method
end
end
l = Lol.new
l.instance_method #=> This will work
l.class_method #=> This will give you an error
Lol.class_method #=> This will work
答
方法self.method_name定义了类的方法。基本上在类定义中把自我看作是指正在定义的类。所以当你说def self.method_name时,你正在定义类本身的方法。
class Foo
def method_name(param)
puts "Instance: #{param}"
end
def self.method_name(param)
puts "Class: #{param}"
end
end
> Foo.new.method_name("bar")
Instance: bar
> Foo.method_name("bar")
Class: bar
尝试接受更多的答案.. – varatis 2012-08-03 14:43:04