0
0
RubyHow-ToBeginner · 3 min read

How to Iterate Over Array in Ruby: Simple Syntax and Examples

In Ruby, you can iterate over an array using the .each method, which runs a block of code for each element. The syntax is array.each do |element| ... end, where element represents each item in the array during iteration.
📐

Syntax

The basic syntax to iterate over an array in Ruby uses the .each method followed by a block. The block receives each element one by one.

  • array: the array you want to loop through
  • .each: method that starts the iteration
  • do |element| ... end: block where element is each item
ruby
array.each do |element|
  # code using element
end
💻

Example

This example shows how to print each fruit name from an array using .each. It demonstrates the simple and readable way to access each item.

ruby
fruits = ["apple", "banana", "cherry"]
fruits.each do |fruit|
  puts fruit
end
Output
apple banana cherry
⚠️

Common Pitfalls

One common mistake is forgetting to use a block with .each, which causes an error. Another is modifying the array inside the loop, which can lead to unexpected results.

Also, using for loops is less idiomatic in Ruby compared to .each.

ruby
numbers = [1, 2, 3]

# Wrong: missing block
# numbers.each

# Right:
numbers.each do |num|
  puts num * 2
end
Output
2 4 6
📊

Quick Reference

Here is a quick summary of common ways to iterate over arrays in Ruby:

MethodDescriptionExample
.eachIterate over each elementarray.each { |e| puts e }
.mapTransform elements and return new arrayarray.map { |e| e * 2 }
.selectFilter elements by conditionarray.select { |e| e > 2 }
for loopLegacy loop syntaxfor e in array do puts e end

Key Takeaways

Use .each with a block to iterate over arrays in Ruby.
The block variable represents each element during iteration.
Avoid modifying the array while iterating to prevent bugs.
.each is preferred over for loops for readability.
Other useful methods include .map and .select for transforming and filtering.