自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Ruby特色之Ruby關(guān)鍵字yield

開發(fā) 開發(fā)工具
Ruby關(guān)鍵字yield在實(shí)際編程中是比較常用的一個(gè)關(guān)鍵字。剛剛學(xué)習(xí)Ruby語言的編程人員們都需要首先掌握這一類的基礎(chǔ)關(guān)鍵字的用法。

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ù)指針...

責(zé)任編輯:曹凱 來源: 博客園
相關(guān)推薦

2009-12-17 13:57:15

Ruby關(guān)鍵字

2013-01-30 10:12:14

Pythonyield

2023-12-11 13:59:00

YieldPython生成器函數(shù)

2009-08-26 09:58:22

C#關(guān)鍵字

2019-12-20 15:19:41

Synchroinze線程安全

2025-01-22 08:06:38

C#yield數(shù)據(jù)迭代

2019-08-29 09:11:38

Pythonyield語法

2009-12-18 11:22:34

Ruby source

2024-03-15 11:52:03

C++關(guān)鍵字編程

2023-11-10 09:29:30

MySQLExplain

2021-08-15 08:11:54

AndroidSynchronize關(guān)鍵字

2011-06-27 15:08:15

SEO

2009-08-21 14:58:56

C# this關(guān)鍵字

2018-04-20 15:56:09

Pythonglobal關(guān)鍵字

2009-09-02 09:24:03

C# this關(guān)鍵字

2009-09-17 09:30:00

Linq LET關(guān)鍵字

2012-03-01 12:50:03

Java

2022-01-04 16:35:42

C++Protected關(guān)鍵字

2009-12-15 17:53:18

Ruby標(biāo)準(zhǔn)庫

2009-12-18 13:13:59

Ruby on Rai
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)