在ruby第二章里面有一段话:
" This is pretty interesting and important, and so if you weren't
paying attention before, you should probably start now."
讲的就是yield这个关键字所传达的东西,这也是ruby比较有特色的一个地方
输入
    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
对这个yield的用法,网上说法不一,有的说是占位符,有的说是"让路",有的说是宏
http://www.javaeye.com/topic/31752
http://axgle.javaeye.com/blog/31018
在我这个.net开发者看来,更愿意把他看成是个方法委托,用.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"); }
   //调用
    call_block(test);
哈哈,上面的代码似乎要比ruby的冗余很多,但是也要严格很多,不知道我这样的分析对不对,不过还是不能完全代替,如果函数中定义一个变量:
    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
也就是说这个代理要获得对上下文作用域的访问权,这在.net里恐怕实现不了,这就有点像一个宏了,甚至是代码织入,不过宏好像不能搞方法传递吧。因
此,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
嘿嘿,这些实现.net委托都可以搞定,给个函数指针...
posted on 2007-04-03 01:21  sharpedge  阅读(3122)  评论(2编辑  收藏  举报