Ruby Iterators

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Ruby Iterators

Iterator is a concept used in object-oriented language. Iteration means doing one thing many times like a loop.

The loop method is the simplest iterator. They return all the elements from a collection, one after the other. Arrays and hashes come in the category of collection.


Ruby Each Iterator

The Ruby each iterator returns all the elements from a hash or array.

Syntax:

  1. (collection).each do |variable|  
  2.   code...  
  3. end  

Here collection can be any array, range or hash.

Example:

  1. #!/usr/bin/ruby   
  2. (1...5).each do |i|   
  3.    puts i   
  4. end

Output:

Ruby iterators 1

Ruby Times Iterator

A loop is executed specified number of times by the times iterator. Loop will start from zero till one less than specified number.

Syntax:

  1. x.times do |variable|  
  2.   code...  
  3. end  

Here, at place of x we need to define number to iterate the loop.

Example:

  1. #!/usr/bin/ruby   
  2. 5.times do |n|   
  3.   puts n   
  4. end   

Output:

Ruby iterators 2

Ruby Upto and Downto Iterators

An upto iterator iterates from number x to number y.

Syntax:

Output:

Ruby iterators 3

Ruby Step Iterator

A step iterator is used to iterate while skipping over a range.

Syntax:

  1. (controller).step(x) do |variable|  
  2.   code  
  3. end 

Here, x is the range which will be skipped during iteration.

Example:

  1. #!/usr/bin/ruby   
  2. (10..50).step(5) do |n|   
  3.   puts n   
  4. end  

Output:

Ruby iterators 4

Ruby Each_Line Iterator

A each_line iterator is used to iterate over a new line in a string.

Example:

  1. #!/usr/bin/ruby   
  2. "All the words are printed in a newline.".each_line do |line|   
  3. puts line   
  4. end 

Output:

Ruby iterators 5