Ruby - Iterators
Iterators are nothing but methods supported by collections. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be termed collections.
Iterators return all the elements of a collection, one after the other. We will be discussing two iterators here, each and collect. Let's look at these in detail.
The each iterator returns all the elements of an array or a hash.
collection.each do |variable|
code
end
|
Executes code for each element in collection. Here, collection could be an array or a ruby hash.
#!/usr/bin/ruby
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
|
Output
1
2
3
4
5
|
You always associate the each iterator with a block. It returns each value of the array, one by one, to the block. The value is stored in the variable i and then displayed on the screen.
The collect iterator returns all the elements of a collection.
collection = collection.collect
|
The collect method need not always be associated with a block. The collect method returns the entire collection, regardless of whether it is an array or a hash.
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = Array.new
b = a.collect
puts b
|
Output
1
2
3
4
5
|
NOTE − The collect method is not the right way to do copying between arrays. There is another method called a clone, which should be used to copy one array into another array.
You normally use the collect method when you want to do something with each of the values to get the new array. For example, this code produces an array b containing 10 times each value in a
#!/usr/bin/ruby
a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b
|
Output
10
20
30
40
50
|
Ruby program to add two integer numbers
how to create an array with Array.[](*args) in Ruby ?
What are the various Ruby runtimes, and how are they different?
Ruby program to check whether the given number is prime or not
Ruby program to reverse a string
Ruby program to check whether the given number is palindrome
Ruby program to print Fibonacci series
How to Replace array elements in Ruby?
Ruby program to print an array
Ruby program to check whether the given number is Armstrong
Program to Print Triangle of Numbers in Ruby
How to add/remove elements to Array in Ruby?
How to shuffle an array in Ruby?
Creating Array with Array.new(size, obj) in Ruby
Ruby program to generate random numbers
Ruby program to Calculate the factorial of given number
What are #method_missing and #send? Why are they useful?
How to Sort Array in Ruby?
How to get index of array element in Ruby
How to Get Input with Gets in Ruby
How to create two dimensional array in ruby?