2011-08-14 28 views

回答

4
def test(&block) ... 

意味着我們的方法接受塊:

def test(number, &block) 
    yield number 
    # same as 
    # block.call number 
end 
test(10) {|a| a+a} 
#=> 20 
# or 
block = proc{|a| a*a} 
test 10, &block 
#=> 100 

雖然def test(:&param)將拋出異常。

您也可以撥打像method(&:operator)

[1,2,3].inject(&:+) 
#=> 6 

這是一樣的

[1,2,3].inject{|sum, i| sum+i } 
+2

這並不意味着你的方法接受一個塊,這意味着你要存儲在Proc對象,如果它被傳遞 - 你不想要的,除非你要傳遞塊到另一個方法或存儲它以備後用。 –

+0

@Monouïe,謝謝,要重讀picaxe – fl00r

6

區別在於def test(:&param)會導致語法錯誤,而def test(&param)不會。

相關問題