Each
The simplest iterator is to access all elements collected continuously.
[1,3,5,7,9].each { |i| puts i }
Output result:
1
3
5
7
9
The unique function is to implement the for loop of the Ruby language. Because the built-in loop primitives in Ruby only include while and. For is just a syntax block. For example:
for song in songlist song.playend
Ruby will use the each iterator to convert:
songlist.each do |song| song.playend
Collect
It obtains each element from the collection and passes it to the block. The result returned by block is used to generate a new array, for example:
["H", "A", "L"].collect {|x| x.succ}
Output result:
["I", "B", "M"]
Inject
Although the name is not easy to understand, it is also a useful iterator that allows you to traverse all the members of a mobile phone to accumulate a value. For example:
[1,3,5,7].inject(0) {|sum,element| sum+element} --> 16[1,3,5,7].inject(1) {|product,element| product*element} –> 105