0
A
回答
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
相關問題
- 1. 如何將參數從一個動作傳遞給其他
- 2. 如何在其他函數中使用cmd傳遞參數?
- 3. 如何使用Gradle將其他參數傳遞給transformClassesWithDexForDebug?
- 4. 如何使一個類參數傳遞給其他方法可見的類
- 5. 傳遞一個塊作爲參數
- 6. 如何將其他參數傳遞給jQuery DataTable ajax調用?
- 7. 如何將參數傳遞給從其他類調用的ViewController
- 8. 如何傳遞其他參數用於分頁
- 9. 其他參數傳遞給控制器
- 10. 其他參數傳遞路線(expressjs)
- 11. e.parameters與其他參數傳遞
- 12. 將其他參數傳遞給方法
- 13. Java,將參數從一個類傳遞到其他類
- 14. 如何使用其他函數將參數傳遞到函數中?
- 15. 傳遞函數作爲參數傳遞給其他功能
- 16. 的Makefile:使用一個命令的輸出作爲參數傳遞給其他
- 17. 如何將可變參數傳遞給其他函數
- 18. 如何將其他參數傳遞給謂詞函數?
- 19. 如何將參數從一個頁面傳遞到其他頁面?
- 20. 如何將參數從一個區域傳遞到其他區域
- 21. 如何將變量從一個ajax函數傳遞到其他
- 22. 傳遞一個URL參數,使用Javascript
- 23. 傳遞幾個參數lapply的FUN(和其他*適用)
- 24. 如何傳遞一個塊作爲if語句的參數?
- 25. 如何傳遞一個模塊作爲cython中struct的參數?
- 26. 如何在其他方法調用中使用傳遞的參數?
- 27. 是否可以使用httpify傳遞其他參數?
- 28. 如何傳遞參數作爲模塊
- 29. 傳遞作爲參數傳遞給其他方法
- 30. jQuery:將$ this與其他參數一起傳遞給函數
'測試(1){放 「你好」}' – fl00r