Up to now,I know four iterator methods.They are each,find,collect and inject.
The each method access every element in collections and pass each element to the block which is defined by two braces or do/end.Then you can use the element in block and deal with them by any way.
The find method access every element and will return the first element which matchs the passed condition in block.If you use this method to find some value in a collection,it will only return the first value neither all the values which match the condition.
The collect method takes each element from the collection and passes it to the block.The results retured by the block are used to construct a new array.
The inject method lets you accumulate a value across the members of a collection.
The each method access every element in collections and pass each element to the block which is defined by two braces or do/end.Then you can use the element in block and deal with them by any way.
ruby Code
- @songs.each {|song| compareSongs.push(song) if song.name == title}
The find method access every element and will return the first element which matchs the passed condition in block.If you use this method to find some value in a collection,it will only return the first value neither all the values which match the condition.
ruby Code
- @songs.find {|song| title == song.name}
ruby Code
- [1, 3, 5, 7, 9].find {|v| v*v > 30 } ! 7
The collect method takes each element from the collection and passes it to the block.The results retured by the block are used to construct a new array.
ruby Code
- ["H", "A", "L"].collect {|x| x.succ } ! ["I", "B", "M"]
The inject method lets you accumulate a value across the members of a collection.
ruby Code
- [1,3,5,7].inject(0) {|sum, element| sum+element} ! 16
- [1,3,5,7].inject(1) {|product, element| product*element} ! 105
本文介绍了Ruby中的四种迭代器方法:each、find、collect和inject。详细解释了每种方法的工作原理及其应用场景,并通过示例代码展示了如何使用这些方法来处理集合数据。
109

被折叠的 条评论
为什么被折叠?



