You may not realize it, but PHP’s array implementation is one of the most power and robust data structures of any language. It’s a strong opinion but you’ll see soon that Ruby actually splits what we call arrays into 2 concepts.

In PHP, you instantate an array like so:

    $food = ['sushi', 'pad thai', 'ramen'];

Or like so:

    $food = array('sushi', 'pad thai', 'ramen');

The former becoming far more common than the later, since its introduction in PHP 5.4, just because of less keystrokes.

Checkout how Ruby does arrays:


    food = ['sushi', 'pad thai', 'ramen']

No this isn’t a trick. It’s really that similar. Feeling pretty confident yet?

Adding New Entries to Arrays

Sometimes, you want to add a new entry to an array. It’s a common thing.

In PHP, you’ll see this kind of notation to add a new thing to an array:

    $food = ['sushi', 'pad thai', 'ramen'];

    $food[] = 'chicken tikki masala';

    echo join(', ', $food);

    => 'sushi, pad thai, ramen, chicken tikki masala'

Ruby has a slightly different annotation, and in a way makes a little more sense:


    food = ['sushi', 'pad thai', 'ramen']

    food << 'chicken tikki masala'

    food.join(', ', food)

    => 'sushi, pad thai, ramen, chicken tikki masala'

The << means add to this Array. It’s a very strangle looking set of symbols to look at first but it will soon click.

To recap, in PHP we use $array[] = 'thing' to add a thing to an array because whatever we place between the brackets will define the key to find the 'thing' in the Array.

Which leads us to the next section.

Associative Arrays and Hashes

There’s going to be the first major difference that’s going to throw you for a tiff. In PHP we’re spoiled with the concept of Arrays and Associative Arrays in the same construct.

Take our lovely $food array from earlier. Say you wanted to add a key => value pair to it; just because you need to. PHP’s Array definition doesn’t care, it welcomes this new entry with open arms:

    $food['peruvian'] = 'cuya'; 
    print_r($food);

    => Array
    (
        [0] => sushi
        [1] => pad thai
        [2] => ramen
        ['peruvian'] => 'cuya';
    )

However, Ruby doesn’t believe in those kind of shinanigans.


    food['peruvian'] = 'cuya'

    => TypeError: no implicit conversion of String into Integer

I know, that error is so unhelpful to us PHP developers. But basically Ruby (like Python) has a separate concept for key => value stores. They’re called Hashes.

Here’s a simple 1 key hash:


    food = { 'peruvian' => 'cuya' }

And it works like you’d expect when you attempt to access it:


    food['peruvian']

    => 'cuya'

Hashes and Arrays in Ruby have very similar API’s for interation, mapping, reducing, etc.

Otherwise, the concept is essentially the same.