语法:
block_name{ statement1 statement2 .......... }
在这里,将学习如何通过使用一个简单的 yield 语句调用块。还将学习使用yield语句具有参数调用块。将检查的示例代码,这两种类型的 yield 语句。
yield 语句:
让我们来看看在yield语句的一个例子:
#!/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 method You are in the block You are again back to the method You 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 语句写到后面跟着参数。甚至可以传递多个参数。在该块中放置在两条垂直线之间的变量(| |)接收的参数。因此,在上面的代码中,yield5语句将试块作为一个参数值5。
现在看看下面的语句:
test {|i| puts "You are in the block #{i}"}
在这里,在变量i中的值为5。现在遵守以下 puts 语句:
puts "You are in the block #{i}"
puts 语句的输出是:
You are in the block 5
如果想超过一个参数,然后yield语句就变成了:
yield a, b
那么块是:
test {|a, b| statement}
这些参数将用逗号隔开。
块和方法:
我们已经看到了如何将一个块和方法关联。通常调用块从块具有相同名称的方法,通过使用yield语句。因此,编写:
#!/usr/bin/ruby def test yield end test{ puts "Hello world"}
这个例子是最简单的方式来实现一个块。调用块 test 使用yield语句。
但是,如果最后一个参数的方法前面加上&,那么可以通过一个块这种方法,此块将被分配到最后一个参数。
*和&在参数列表中&还在后面。
#!/usr/bin/ruby def test(&block) block.call end test { puts "Hello World!"} This will produce following result: Hello World!
BEGIN 和 END 块
每一个Ruby源文件都可以声明的代码块作为文件被加载运行(BEGIN块)后,该程序已执行完毕(END块)。
#!/usr/bin/ruby BEGIN { # BEGIN block code puts "BEGIN code block" } END { # END block code puts "END code block" } # MAIN block code puts "MAIN code block"
一个程序可能包括多个BEGIN和END块。 BEGIN块以遇到它们的顺序执行。 END块以相反的顺序执行。上述程序执行时,会产生以下结果:
BEGIN code block MAIN code block END code block
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
- 《战神5》PC版评测:轻推W缓慢前行
- 《阿瑞亚之旅》评测:更适合佛系玩家体质的跑团
- 黑神话悟空浮屠界紫门怎么开 浮屠界紫门打开方法介绍
- 黑神话悟空龟泪怎么获得 黑神话悟空龟泪获得方法介绍
- 黑神话悟空怎么获得还魂丹 黑神话悟空还魂丹获取方法一览
- HiFi顶级人声天碟《试音齐秦》wav
- 张敬轩.2012-WhyNot(EP)【环球】【WAV+CUE】
- 张小英1988-情愁[新加坡复黑版][WAV+CUE]
- 游民金币礼品补货啦 Steam充值卡等你兑换!
- 《暗喻幻想:ReFantazio》M站均分94分 近年最好的RPG游戏之一
- 今年第一项诺贝尔奖揭幕 生理学或医学奖揭晓
- 《梁静茹 华语乐坛情歌天后 爱久见人心》[WAV/分轨][360MB]
- 《田震 绝版珍藏 依然在飞》[WAV+CUE][600MB]
- 《60首经典金曲 4CD》[WAV/分轨][1.4GB]
- 赵传.1988-我很丑,可是我很温柔【滚石】【WAV+CUE】