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  

你可能感兴趣的:(Access,Ruby,UP)