Iterators in Ruby

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.
ruby Code
  1. @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
 
  1. @songs.find {|song| title == song.name}  
ruby Code
 
  1. [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
 
  1. ["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. [1,3,5,7].inject(0) {|sum, element| sum+element} ! 16  
  2. [1,3,5,7].inject(1) {|product, element| product*element} ! 105  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值