2014-01-27 31 views
2

命名作用域(或Rails 4中的作用域),Lambdas和Procs之間的區別是什麼?命名作用域,Lambdas和Procs之間的區別

在Lambda和Proc之間,選擇哪一個?

+2

http://stackoverflow.com/questions/626/when-to-use-lambda-when-to-use-proc-new http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/ – Muntasim

回答

7

1. PROC不檢查傳遞的參數,但拉姆達確實

proc1 = Proc.new { |a, b| a + 5 } 

proc1.call(2)  # call with only one parameter 
=> 7    # no error, unless the block uses the 2nd parameter 

lambda1 = lambda { |a, b| a + 5 } 

lambda1.call(2) 
=> ArgumentError: wrong number of arguments (1 for 2) 

僅當塊使用第二PARAM PROC將拋出錯誤。

proc2 = Proc.new { |a, b| a + b } 

proc2.call(2)  # call with only one parameter 
=> TypeError: nil can't be coerced into Fixnum 

2. PROC從調用方法返回,而拉姆達不

def meth1 
    Proc.new { return 'return from proc' }.call 
    return 'return from method' 
end 

puts meth1 
=> return from proc 

def meth2 
    lambda { return 'return from lambda' }.call 
    return 'return from method' 
end 

puts meth2 
=> return from method 

如果它們沒有一個方法叫做內部,

proc1 = Proc.new { return "Thank you" } 

proc1.call 
=> LocalJumpError: unexpected return 

lambda1 = lambda { return "Thank you" } 

lambda1.call 
=> "Thank you" 

3.作用域/命名示波器是Rails的一項功能

它被用作方法調用的關聯對象或模型

例如,在user.rb指定哪些可以參照常用查詢:

scope :developers, -> { where(:role => 'developer') } 

你可以使用它作爲

@developers = User.developers 

範圍是可鏈接的,所以你可以做查詢,如

@developers = User.developers.where(:age => 40) 

示例中定義的作用域與定義類方法完全相同,如下所示。

def self.developers 
    where(:role => 'developer') 
end 
+1

謝謝你清楚地解釋一切! – Pavan

相關問題