时间:2021-05-23
Iterator
定义
A Ruby iterator is simple a method that can invoke a block of code.
上面代码中的 yield 之后的 i1 会作为 parameter 传入到 block 中, 赋值给 block 的 argument f。
Block 中可以有多个 arguments.
常见的 iterator
each
each is probable the simplest iterator - all it does is yield successive elements of its collection.
[1, 3, 5, 7, 9].each { |i| puts i }# 1 # 3# 5# 7# 9find
A blocl may also return a value to the method. The value of the last expression evaluated in the block is passed back to the method as the value of the yield.
class Array def find each do |value| return value if yield(value) end endend[1,3,4,7,9].find { |v| V*V > 30 } # => 7collect (also known as map)
Which takes each element from the collection and passes it to the block. The results returned by the block are used to construct a new array
["H", "A", "L"].collect { |x| x.succ } # => ["I", "B", "M"]inject
The inject method lets you accumulate a value across the members of a collection.
[1,3,5,7].inject { |sum, element| sum + element } # => 16# sum = 1, element = 3# sum = 4, element = 5# sum = 9, element = 7# sum = 16[1,3,5,6].inject { |product, element| product*element } # => 105If inject is called with no parameter, it uses the first element of the collections as the initial value and starts the iteration with the second value.
上面代码的另一种简便写法:
[1,3,5,7].inject(:+) # => 16[1,3,5,7]/inject(:*) # => 105Iterator 和 I/O 系统的交互
Iterators 不仅仅能够访问 Array 和 Hash 中的数据, 和可以和 I/O 系统交互
f = File.open("testfile")f.each do |line| puts "The line is: #{line}"endf.closeproduces:
The line is: This is line one
The line is: This is line two
The line is: This is line three
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了python中迭代器(iterator)用法。分享给大家供大家参考。具体如下:#---------------------------------
本文实例讲述了PHP预定义接口——Iterator用法。分享给大家供大家参考,具体如下:Iterator(迭代器)接口可在内部迭代自己的外部迭代器或类的接口。接
在介绍yield前有必要先说明下Python中的迭代器(iterator)和生成器(constructor)。一、迭代器(iterator)在Python中,f
迭代器Iterator接口1.迭代器接口Iterable内置方法iterator(),返回一个新建的Iterator。如:publicinterfaceIter
我们知道迭代器(Iterator)是一种对象,它能够用来遍历标准模板库容器中的部分或全部元素。那么Iterator迭代器的设计原理是什么呢?迭代器问什么定义了一