ruby
  1. ruby-iterators

Ruby Iterators

Iterators are a vital part of Ruby, allowing you to loop through collections and execute code for each item in the collection. In this tutorial, we will cover various iterators in Ruby.

Syntax

Ruby iterators syntax varies depending on the type of iterator. Here is a basic syntax for a block iterator:

collection.each do |variable|
  # code to execute for each item in the collection
end

Here, collection is the object you want to loop through, variable is the variable name that represents each item in the collection, and the code between do and end is the code that will be executed for each item in the collection.

Example

Let's look at an example of using a block iterator to loop through an array of numbers:

numbers = [1, 2, 3, 4, 5]

numbers.each do |num|
  puts num
end

Output

1
2
3
4
5

Explanation

In this example, numbers is an array of integers. The each method is called on the numbers array, and a block of code is passed in. The block of code uses the |num| syntax to represent each element of the array. The puts method is called on each element of the array, which prints it to the console.

Use

Iterators are used in Ruby to loop through collections such as arrays, hashes, and ranges. They allow you to execute code for each item in the collection without having to write repetitive code.

Important Points

  • There are many types of iterators in Ruby, such as each, times, upto, downto, and map.
  • Blocks are used to define the code to be executed for each item in the collection.
  • The block parameter syntax (|variable|) is used to represent each item in the collection.

Summary

In this tutorial, we covered the basics of Ruby iterators, including their syntax, example usage, output, and important points. With this knowledge, you should be able to write clean and efficient Ruby code using iterators.

Published on: