Ruby特色之Ruby關(guān)鍵字yield
Ruby語言中有些基礎(chǔ)關(guān)鍵字是初學(xué)者們必須要掌握的基礎(chǔ)知識(shí)。在這里我們就來一起了解一下具有特色的Ruby關(guān)鍵字yield的相關(guān)知識(shí)。#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
對(duì)這個(gè)yield的用法,網(wǎng)上說法不一,有的說是占位符,有的說是"讓路",有的說是宏
http://www.javaeye.com/topic/31752
http://axgle.javaeye.com/blog/31018
在我這個(gè).net開發(fā)者看來,更愿意把他看成是個(gè)方法委托,用.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"); }- //調(diào)用
- call_block(test);
哈哈,上面的代碼似乎要比ruby的冗余很多,但是也要嚴(yán)格很多,不知道我這樣的分析對(duì)不對(duì),不過還是不能完全代替,如果函數(shù)中定義一個(gè)變量:
- 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
也就是說這個(gè)代理要獲得對(duì)上下文作用域的訪問權(quán),這在.net里恐怕實(shí)現(xiàn)不了,這就有點(diǎn)像一個(gè)宏了,甚至是代碼織入,不過宏好像不能搞方法傳遞吧。因 此,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
嘿嘿,這些實(shí)現(xiàn).net委托都可以搞定,給個(gè)函數(shù)指針...