[2014年学习计划之RoR系列] 第二步 – 熟悉Ruby语言 (2/n) Blocks and Iterators (代码块和迭代器)
[就算没有含金量,也请尊重原创, 转载自我的独立博客http://brucejia.net]
Blocks and Iterators (代码块和迭代器)
代码块和迭代器是Ruby语言中比较有特点的东西。先看代码块吧,如下面代码所示,代码块通常是由大括号({和}) 或者do/end包起来的一段代码。
1: { puts "Hello" } # this is a block
2: do ###
3: club.enroll(person) # and so is this
4: person.socialize #
5: end ###
建议:单行的block用大括号;多行的block用do/end
blocks可以用来实现回调函数和迭代器。
1: def call_block
2: puts "Start of method"
3: yield
4: yield
5: puts "End of method"
6: end
7:
8: call_block { puts "In the block" }
注意代码中的yield关键字。上边的代码产生结果如下:
Start of method
In the block
In the block
End of method
yield会调用跟方法(method)相关联的block,可以调用一次或多次。
当然block也可以带有自己的参数
1: call_block {|str, num| ... }
调用的时候将参数传入给yield就好了。 - 这个时候yield看起来像个函数了。
1: def call_block
2: yield("hello", 99)
3: end
动手试试看这两行代码会输出什么。
1: animals = %w( ant bee cat dog elk ) # create an array
2: animals.each {|animal| puts animal } # iterate over the contents
If you love him, teach him C++, for it's heaven;
If you hate him, teach him C++, for it's hell
If you hate him, teach him C++, for it's hell
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步