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

相关问题