[2014年学习计划之RoR系列] 第二步 – 熟悉Ruby语言 (2/n) Blocks and Iterators (代码块和迭代器)
来源:互联网 发布:淘宝网开通淘金币活动 编辑:程序博客网 时间:2024/06/05 03:14
[就算没有含金量,也请尊重原创, 转载自我的独立博客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
0 0
- [2014年学习计划之RoR系列] 第二步 – 熟悉Ruby语言 (2/n) Blocks and Iterators (代码块和迭代器)
- [2014年学习计划之RoR系列] 第二步 – 熟悉Ruby语言 (3/n)
- [2014年学习计划之RoR系列] 第二步 - 熟悉Ruby语言 (1/n)
- [2014年学习计划之RoR系列] 第一步 - 搭建开发环境
- ruby代码块和迭代器
- Ruby: 学习日志3: Containers, Blocks, Iterators
- 《programming ruby中文版第二版》——代码块、迭代器、类和对
- 《programming ruby中文版第二版》——代码块 迭代器
- Ruby yield and block and Iterators
- Ruby入门之代码块、迭代子和过程对象
- ruby 块 和 迭代器
- ruby的Proc和代码块(Block)
- ruby 的代码块和yield
- OC:代码块(blocks)
- ruby代码块
- ruby 代码块
- ruby 的代码块
- ruby语言中代码块作为方法的参数使用
- js中null和 document.getElementById("userId")小结
- DevExpress的文本框 只能输入保留2位小数的正数字
- CF223A题Sereja and Dima
- android service被系统回收的解决方法
- 工作记录
- [2014年学习计划之RoR系列] 第二步 – 熟悉Ruby语言 (2/n) Blocks and Iterators (代码块和迭代器)
- warning: incompatible implicit declaration of built-in function 'exit'
- 读《重构》,学习Collections.unmodifiableList()用法
- libevent源代码分析--event_dispatch() (一)
- ApplicationContextAware动态获取spring bean
- HDU 3359高斯消元
- WPF画红色波浪线
- DevExpress的DateEdit设置显示日期和时间
- C++编程思想笔记