Ruby Iteration Methods
Iterators are the methods which are supported by collections (Arrays, or Hashes). Collections are objects which store a group of data members. Ruby iterators return all the elements of a collection one after another. For example, I have an array of numbers and I want to multiply each number in the array by 2. Array= [1,2,3,4] and I want to get Array= [2,4,6,8]. I can use ruby iterator methods to do that. There are many iterators in Ruby (each, collect, map, times, upto, downto, step, each_line).
I will talk about each and collect/map methods (map and collect are the same). Both each and collect are helpful methods for iterating through when you want to make changes that affect each element in an array or hash. Each method yields and returns the original array
Example:
array= [1,2,3,4]
def multiply (array)
array.each {|x| puts x*2}
end
prints 2,4,6,8 and returns [1,2,3,4] no matter what
If I want to change the return value of each method, I should tell it to do so.
Example:
array= [1,2,3,4]
def multiply (array)
new_array = []
array.each do |num|
new_array << num*2
end
new_array
end
this will return [2,4,6,8]
Collect/map method creates a new array and pushes the results of the block into it; then it returns this new array.
Example:
array= [1,2,3,4]
def multiply (array)
array.collect {|x| puts x*2}
end
prints 2,4,6,8 and returns [nil,nil,nil,nil]. It returns nil because of “puts” who is return value is always nil to avoid that I can do
Example:
array= [1,2,3,4]
def multiply (array)
array.collect {|x| x*2}
end
return value is [2,4,6,8].
If I need to use the result of my iteration method to write a code that depend on that result, it is better to use collect/map because it returns a new array in other word the array that passed a specific test, else I can just use each.