日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

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

新聞中心

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

Ruby語言中有些基礎(chǔ)關(guān)鍵字是初學(xué)者們必須要掌握的基礎(chǔ)知識(shí)。在這里我們就來一起了解一下具有特色的Ruby關(guān)鍵字yield的相關(guān)知識(shí)。#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

對(duì)這個(gè)yield的用法,網(wǎng)上說法不一,有的說是占位符,有的說是"讓路",有的說是宏
http://www.javaeye.com/topic/31752
http://axgle.javaeye.com/blog/31018
在我這個(gè).net開發(fā)者看來,更愿意把他看成是個(gè)方法委托,用.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的冗余很多,但是也要嚴(yán)格很多,不知道我這樣的分析對(duì)不對(duì),不過還是不能完全代替,如果函數(shù)中定義一個(gè)變量:

 
 
 
  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

也就是說這個(gè)代理要獲得對(duì)上下文作用域的訪問權(quán),這在.net里恐怕實(shí)現(xiàn)不了,這就有點(diǎn)像一個(gè)宏了,甚至是代碼織入,不過宏好像不能搞方法傳遞吧。因 此,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

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


本文標(biāo)題:Ruby特色之Ruby關(guān)鍵字yield
鏈接地址:http://www.5511xx.com/article/dpegihs.html