日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Ruby特色之Ruby關(guān)鍵字yield

Ruby語言中有些基礎(chǔ)關(guān)鍵字是初學(xué)者們必須要掌握的基礎(chǔ)知識。在這里我們就來一起了解一下具有特色的Ruby關(guān)鍵字yield的相關(guān)知識。#t#
輸入

  1. def call_block   
  2. puts "Start of method"   
  3. yield   
  4. yield   
  5. puts "End of method"   
  6. end   
  7. call_block { puts "In the block" }  

輸出:
Start of method
In the block
In the block
End of method

對這個yield的用法,網(wǎng)上說法不一,有的說是占位符,有的說是"讓路",有的說是宏
http://www.javaeye.com/topic/31752
http://axgle.javaeye.com/blog/31018
在我這個.net開發(fā)者看來,更愿意把他看成是個方法委托,用.net寫,可以寫成這樣
輸入

 
 
 
  1. delegate outhandler();   
  2. void call_block(outhandler yield)   
  3. {   
  4. Console.WriteLIne("Start of method");   
  5. yield();   
  6. yield();   
  7. Console.WriteLIne("End of method");   
  8. }   
  9. void test(){Console.WriteLine
    ("In the block"); }   
  10. //調(diào)用   
  11. call_block(test);  

哈哈,上面的代碼似乎要比ruby的冗余很多,但是也要嚴格很多,不知道我這樣的分析對不對,不過還是不能完全代替,如果函數(shù)中定義一個變量:

 
 
 
  1. def call_block   
  2. puts "Start of method"   
  3. @count=1   
  4. yield   
  5. yield   
  6. puts "End of method"   
  7. end   
  8. call_block { puts @count=@count+1 }  

輸出:
Start of method
2
3
End of method

也就是說這個代理要獲得對上下文作用域的訪問權(quán),這在.net里恐怕實現(xiàn)不了,這就有點像一個宏了,甚至是代碼織入,不過宏好像不能搞方法傳遞吧。因 此,ruby的yield還是很有特色,看看他使用的一些例子:
輸入

 
 
 
  1. [ 'cat', 'dog', 'horse' ].each
     {|name| print name, " " }   
  2. 5.times { print "*" }   
  3. 3.upto(6) {|i| print i }   
  4. ('a'..'e').each {|char| print char }  

輸出:
cat dog horse *****3456abcde

嘿嘿,這些實現(xiàn).net委托都可以搞定,給個函數(shù)指針...


網(wǎng)站名稱:Ruby特色之Ruby關(guān)鍵字yield
當(dāng)前路徑:http://www.dlmjj.cn/article/dpegihs.html