Ruby - Array Array Iteration

Introduction

The each method goes through each element of the array and passes it as a parameter to the code block.

For example:

Demo

[1, "test", 2, 3, 4].each { |element| puts element.to_s + "X" }

Result

You can convert an array on the fly using the collect method:

Demo

[1, 2, 3, 4].collect { |element| element * 2 }

collect method iterates through an array element by element, and assigns to that element the result of any expression within the code block.

In this example, you multiply the value of the element by 2.

Related Topics

Exercise