Ruby特色之Ruby关键字yield

开发 开发工具
Ruby关键字yield在实际编程中是比较常用的一个关键字。刚刚学习Ruby语言的编程人员们都需要首先掌握这一类的基础关键字的用法。

Ruby语言中有些基础关键字是初学者们必须要掌握的基础知识。在这里我们就来一起了解一下具有特色的Ruby关键字yield的相关知识。#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的用法,网上说法不一,有的说是占位符,有的说是"让路",有的说是宏
http://www.javaeye.com/topic/31752
http://axgle.javaeye.com/blog/31018
在我这个.net开发者看来,更愿意把他看成是个方法委托,用.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. //调用   
  11. call_block(test);  

哈哈,上面的代码似乎要比ruby的冗余很多,但是也要严格很多,不知道我这样的分析对不对,不过还是不能完全代替,如果函数中定义一个变量:

  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

也就是说这个代理要获得对上下文作用域的访问权,这在.net里恐怕实现不了,这就有点像一个宏了,甚至是代码织入,不过宏好像不能搞方法传递吧。因 此,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

嘿嘿,这些实现.net委托都可以搞定,给个函数指针...

责任编辑:曹凯 来源: 博客园
相关推荐

2009-12-17 13:57:15

Ruby关键字

2013-01-30 10:12:14

Pythonyield

2023-12-11 13:59:00

YieldPython生成器函数

2009-08-26 09:58:22

C#关键字

2019-08-29 09:11:38

Pythonyield语法

2019-12-20 15:19:41

Synchroinze线程安全

2009-12-18 11:22:34

Ruby source

2024-03-15 11:52:03

C++关键字编程

2021-08-15 08:11:54

AndroidSynchronize关键字

2023-11-10 09:29:30

MySQLExplain

2011-06-27 15:08:15

SEO

2022-01-04 16:35:42

C++Protected关键字

2009-09-17 09:30:00

Linq LET关键字

2009-09-02 09:24:03

C# this关键字

2012-03-01 12:50:03

Java

2009-12-18 13:13:59

Ruby on Rai

2014-11-05 11:05:15

Ruby

2009-08-21 14:58:56

C# this关键字

2018-04-20 15:56:09

Pythonglobal关键字

2009-12-15 17:53:18

Ruby标准库
点赞
收藏

51CTO技术栈公众号