2016-11-22 41 views

回答

3
test(1){ puts "hello" } 

test(1) do 
    puts "hello" 
end 

blk = proc{ puts "hello" } 
test(1, &blk) 

你可以看看這個https://pine.fm/LearnToProgram/chap_10.html

由於@Cary Swoveland建議大家可以去略深。

任何Ruby方法都可以隱式地接受一個塊。即使你沒有在方法簽名中定義它,你仍然可以捕獲它並進一步傳遞。

因此,考慮這個想法,我們可以做以下用你的方法操作:

def test(args, &block) 
    yield 
end 

相同

def test(args) 
    yield 
end 

與同爲

def test(args) 
    block = Proc.new 
    block.call 
end 

當你有這個隱含的塊捕獲你可能想要添加額外的檢查:

def test(args) 
    if block_given? 
    block = Proc.new 
    block.call 
    else 
    "no block" 
    end 
end 

def test(args) 
    if block_given? 
    yield 
    else 
    "no block" 
    end 
end 

所以調用這些方法將返回如下:

test("args") 
#=> no block 
test("args"){ "Hello World" } 
#=> "Hello World" 
+0

@CarySwoveland DONE – fl00r

相關問題