深入理解 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
- 深入理解 Ruby 关键字 yiald
- 深入理解this关键字
- 深入理解 final 关键字
- 深入理解volatile关键字
- 深入理解volatile关键字
- 深入理解volatile关键字
- 深入理解volitale关键字
- 深入理解final关键字
- Static关键字深入理解
- volatile关键字深入理解
- 深入理解final关键字
- 深入理解volatile关键字
- 深入理解volitale关键字
- 深入理解final关键字
- 深入理解volatile关键字
- 深入理解volitile关键字
- 深入理解explicit关键字
- 深入理解volatile关键字
- hduoj 1312
- 手把手教你做产品经理
- linux shell的iconv
- Codeforces 727D
- Android Service创建USB HOST通信
- 深入理解 Ruby 关键字 yiald
- Android四大组件之BroadcastReceiver
- 文章标题
- xUtils系列之BitmapUtils
- 收藏的几个链接
- Verilog 编程实验(6)-4位移位寄存器的设计与实现
- 【OpenCL编程任务一】输出进行运算设备的名称
- JDBC QueryRunner(开源框架)之查询 详解
- 143.Sort Colors II-排颜色 II(中等题)