深入理解 Ruby 关键字 yiald

来源:互联网 发布:淘宝店铺免费模版 编辑:程序博客网 时间:2024/05/17 01:25

yield

  • 是ruby比较有特色的一个地方,本文将具体理解一下yield的用法。
  • 在函数里面的有一条yield语句,到时候执行的时候可以执行函数类外的block。而且这个block可以有自己的context,感觉有点像callback,又有点像c里面的宏定义。
def call_block       puts "Start of method"       yield       yield       puts "End of method"     end     call_block { puts "In the block" } 

结果 yield 将调用表达式后面的block

输出:

 Start of method  In the block  In the block  End of method
 #!/usr/bin/ruby    def test       puts "You are in the method"       yield       puts "You are again back to the method"       yield    end    test {puts "You are in the block"}

输出:

You are in the methodYou are in the blockYou are again back to the methodYou are in the block
    #!/usr/bin/ruby    def test       yield 5       puts "You are in the method test"       yield 100    end    test {|i| puts "You are in the block #{i}"}

这将产生以下结果:
You are in the block 5
You are in the method test
You are in the block 100

在这里,yield 语句后跟着参数。您甚至可以传递多个参数。在块中,您可以在两个竖线之间放置一个变量来接受参数。因此,在上面的代码中,yield 5 语句向 test 块传递值 5 作为参数。
现在,看下面的语句:

test {|i| puts “You are in the block #{i}”}

在这里,值 5 会在变量 i 中收到。现在,观察下面的 puts 语句:

puts “You are in the block #{i}”

这个 puts 语句的输出是:

You are in the block 5

如果您想要传递多个参数,那么 yield 语句如下所示:

yield a, b

此时,块如下所示:

test {|a, b| statement}

但是如果方法的最后一个参数前带有 &,那么您可以向该方法传递一个块,且这个块可被赋给最后一个参数。如果 * 和 & 同时出现在参数列表中,& 应放在后面。

    #!/usr/bin/ruby    def test(&block)       block.call    end    test { puts "Hello World!"}

这将产生以下结果:

引用块内容

Hello World!

0 0