Block 與Proc的區別:ruby
Block是代碼塊,Proc是對象;curl
參數列表中最多隻能有一個Block, 可是能夠有多個Proc或Lambda;函數
Block能夠當作是Proc的一個類實例.url
Proc 與Lambda 區別:.net
Proc和Lambda都是Proc對象;對象
Lambda檢查參數個數,當傳遞的參數超過一個時,會報錯,而Proc不檢查,當傳遞參數多於一個時,只傳遞第一個參數,忽略掉其餘參數;blog
Proc和Lambda中return關鍵字的行爲是不一樣的.get
# Block Examples test
[1,2,3].each { |x| puts x*2 } # block is in between the curly braceslambda
[1,2,3].each do |x| puts x*2 # block is everything between the do and end end
# Proc Examples
p = Proc.new { |x| puts x*2 } [1,2,3].each(&p) # The '&' tells ruby to turn the proc into a block
proc = Proc.new { puts "Hello World" }
proc.call # The body of the Proc object gets executed when called
# Lambda Examples
lam = lambda { |x| puts x*2 }
[1,2,3].each(&lam)
lam = lambda { puts "Hello World" }
lam.call
# 參數傳遞
lam = lambda { |x| puts x } # creates a lambda that takes 1 argument
lam.call(2) # prints out 2 lam.call # ArgumentError: wrong number of arguments (0 for 1)
lam.call(1,2,3) # ArgumentError: wrong number of arguments (3 for 1)
proc = Proc.new { |x| puts x } # creates a proc that takes 1 argument
proc.call(2) # prints out 2
proc.call # returns nil
proc.call(1,2,3) # prints out 1 and forgets about the extra arguments
# Return行爲
# lambda中return跳出lambda,仍然執行lambda外部代碼
def lambda_test
lam = lambda { return }
lam.call puts "Hello world"
end
lambda_test # calling lambda_test prints 'Hello World'
def proc_test
#proc中return直接跳出函數
proc = Proc.new { return }
proc.call
puts "Hello world"
end
proc_test # calling proc_test prints nothing
爲了隨時查閱,沒有侵權意思,望見諒!
文章出處:http://my.oschina.net/u/811744/blog/152802