Ruby equivalents to PHP’s foreach

In PHP, array keys can be either numbers or strings, whereas in Ruby associative arrays are a separate data type, called a hash.

Here’s a cheatsheet for various foreach variants, translated into idiomatic Ruby:

Looping over a numeric array (PHP)

<?php

$items = array( 'orange', 'pear', 'banana' );

# without indexes
foreach ( $items as $item ) {
    echo $item;
}

# with indexes
foreach ( $items as $i => $item ) {
    echo $i, $item;
}

Looping over an array (Ruby)

items = ['orange', 'pear', 'banana']

# without indexes
items.each do |item|
    puts item
end

# with indexes
items.each_with_index do |item, i|
    puts i, item
end

Looping over an associative array (PHP)

<?php

$continents = array(
    'africa' => 'Africa',
    'europe' => 'Europe',
    'north-america' => 'North America'
);

# without keys
foreach ( $continents as $continent ) {
    echo $continent;
}

# with keys
foreach ( $continents as $slug => $title ) {
    echo $slug, $title;
}

Looping over a hash (Ruby)

continents = {
    'africa' => 'Africa',
    'europe' => 'Europe',
    'north-america' => 'North America'
}

# without keys
continents.each_value do |continent|
    puts continent
end

# with keys
continents.each do |slug, title|
    puts slug, title
end

Important note: Unlike in PHP associative arrays, elements inside a Ruby hash are not ordered.

If you’re having a sense of déjà vu, it’s probably because I wrote a similar post a while ago, but for Python.

comments powered by Disqus