Ruby特色之Ruby關鍵字yield
Ruby語言中有些基礎關鍵字是初學者們必須要掌握的基礎知識。在這里我們就來一起了解一下具有特色的Ruby關鍵字yield的相關知識。#t#
輸入
- def call_block
- puts "Start of method"
- yield
- yield
- puts "End of method"
- end
- call_block { puts "In the block" }
輸出:
Start of method
In the block
In the block
End of method
對這個yield的用法,網上說法不一,有的說是占位符,有的說是"讓路",有的說是宏
http://www.javaeye.com/topic/31752
http://axgle.javaeye.com/blog/31018
在我這個.net開發者看來,更愿意把他看成是個方法委托,用.net寫,可以寫成這樣
輸入
- delegate outhandler();
- void call_block(outhandler yield)
- {
- Console.WriteLIne("Start of method");
- yield();
- yield();
- Console.WriteLIne("End of method");
- }
- void test(){Console.WriteLine
("In the block"); }- //調用
- call_block(test);
哈哈,上面的代碼似乎要比ruby的冗余很多,但是也要嚴格很多,不知道我這樣的分析對不對,不過還是不能完全代替,如果函數中定義一個變量:
- def call_block
- puts "Start of method"
- @count=1
- yield
- yield
- puts "End of method"
- end
- call_block { puts @count=@count+1 }
輸出:
Start of method
2
3
End of method
也就是說這個代理要獲得對上下文作用域的訪問權,這在.net里恐怕實現不了,這就有點像一個宏了,甚至是代碼織入,不過宏好像不能搞方法傳遞吧。因 此,ruby的yield還是很有特色,看看他使用的一些例子:
輸入
- [ 'cat', 'dog', 'horse' ].each
{|name| print name, " " }- 5.times { print "*" }
- 3.upto(6) {|i| print i }
- ('a'..'e').each {|char| print char }
輸出:
cat dog horse *****3456abcde
嘿嘿,這些實現.net委托都可以搞定,給個函數指針...