Code Blocks and Iterators in Ruby

Code Blocks in Ruby:

It is an incredibly powerful feature. In Ruby, Code blocks briefly describe chunks of code you can associate with method invocations, almost as if they were parameters. You can use code blocks to implement callbacks, pass around chunks of code, and implement iterators. Code blocks are just chunks of code between braces or between doing and end. It has the following syntax:

{ puts "Hello" }

This is also a code block:

do
club.enroll(person)
person.socialize
end

Code blocks are used throughout the Ruby library to implement iterators which are methods that return successive elements from some kind of collection.

Example:

animals = %w( ant bee cat dog ) # create an array
animals.each {|animal| puts animal } # iterate over the contents

Iterators in Ruby:

In Ruby, an iterator is a simple method that can invoke a block of code. We know that a block may appear only in the source adjacent to a method call and that the code in the block is not executed at the time it is encountered.

Instead, Ruby remembers the context in which the block appears (the local variables, the current object, and so on) and then enters the method. This is where the magic starts. Within the method, the block may be invoked, almost as if it were a method itself, using the yield statement. Whenever a yield is executed, it invokes the code in the block. When the block exits, the control picks back up immediately after the yield.

Example:

def three_times
yield
yield
yield
end
three_times { puts "Hello" }

Output:
produces:
Hello
Hello
Hello

Types of Iterators in Ruby:

There are mainly seven types of iterators in Ruby.
i. Each Iterator
ii. Collect Iterator
iii. Times Iterator
iv. Upto Iterator
v. Downto Iterator
vi. Step Iterator
vii. Each Line Iterator