Code Blocks and Iterators are a very useful feature in Ruby.
An iterator is a method that executes a block of code.
Say we have a method named each
def each(array)
#do something
end
The block is specified next to the method call, after the last parameter to the method.
names=['alice', 'bob', 'charlie', 'dave']
each(names) { |s| puts s }
Our block is the code within the { } braces. (mutiple line block can be written between do….end)
We are passing an array names, in the call each(names).
Inside each() we will iterate through this array names.
def each(arr)
for i in 0..arr.size-1
yield arr[i]
end
end
All the code block iterator’s magic is done by the yield statement.
The yield statement invokes the code in the block.
The yield statement can also pass parameters to the block . In our example, the array element at position i is passed to the block. The block receives this parameter between vertical bars or pipes. (|s| in our example)
A block may also return value to the yield. The last expression evaluated in the block is passed back as the value of the yield.
Here is the complete listing of our code so far
def each(arr)
for i in 0..arr.size-1
yield arr[i]
end
end
names=['alice', 'bob', 'charlie', 'dave']
each(names) { |s| puts s }
This code will print all the array elements, as yield is called for each array element. Yield in turn invokes the code block passing it the array elements, the code block puts the element.
We could change the block code to print all the array element in upper case or in reverse.
each(names) { |s| puts s.upcase }
each(names) { |s| puts s.reverse }
What we have done so far, is actually provided builtin by ruby for various types of collections.
each is a builtin iterator in ruby which yield the elements of the collection.
To print all elements of array names we could simply do
names.each { |name| puts name }
Similarly there is a find iterator.
To print all names that begin with m, we could use
m_names = names.find { |name| name.index('m') == 0 }
m_names.each { |name| puts name }
Iterators help a lot in keeping ruby on rails code compact. I have been using them a lot, ever since i discovered them.