1. Iterators are nothing but special kinds of methods which behaves like loops.
2. e.g. times, upto, downto iterators of integer
1) 3.times {print 'Ruby!' } # Prints 'Ruby! Ruby! Ruby!'
2) 1.upto(9) {|x| print x} # Prints '123456789'
3) 9.downto(1){|n| print n} # Prints '987654321'
3. each, map, select & inject are also Array iterators
2. e.g. times, upto, downto iterators of integer
1) 3.times {print 'Ruby!' } # Prints 'Ruby! Ruby! Ruby!'
2) 1.upto(9) {|x| print x} # Prints '123456789'
3) 9.downto(1){|n| print n} # Prints '987654321'
3. each, map, select & inject are also Array iterators
1) a = [3, 2, 1] # This is an array literal
a[3] = a[2] - 1 # Use square brackets to query & set array elementsa.each do |elt| # each is an iterator. The block has a parameter elt
print elt+1 # prints '4321'
end # This block was delimited with do/end instead of {}
2) a = [1, 2, 3, 4] # Start with an array
b = a.map {|x| x*x} # Square elements: b is [1, 4, 9, 16]
c = a.select {|x| x%2==0|} # Select even elements: c is [2, 4]
a.inject do |sum,x| # Compute the sum of the elements => 10
sum + x
end
4. each is an iterator of Hash as well
No comments:
Post a Comment