2012-08-03 109 views
2

我一直在研究Rails的時間不長,直到現在....所以如果有隨時糾正我rails不同的方式定義方法

我看到有兩種方式在導軌

  1. def method_name(param)
  2. def self.method_name(param)

的差限定的方法(如我明白)是1主要用於在控制器而2中使用模型...但偶爾我碰到模型的方法,像'1的定義。

你能向我解釋兩種方法的主要區別嗎?

+0

嘗試接受更多的答案.. – varatis 2012-08-03 14:43:04

回答

4

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 
2

方法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