Exercise 34. Accessing Elements of Arrays

Arrays are pretty useful, but unless you can get at the things in them, they aren’t all that useful. You can already go through the elements of an array in order, but what if you want the fifth element? You need to know how to access the elements of an array. Here’s how you would access the first element of an array:

animals = ['bear', 'tiger', 'penguin', 'zebra'] bear = animals[0]

You take an array of animals, and then you get the first (1st) one using 0?! How does that work? Because of the way math works, Ruby starts its arrays at 0 rather than 1. It seems weird, but there are many advantages to this, even though it is mostly arbitrary.

The best way to explain why is by ...

Get Learn Ruby the Hard Way: A Simple and Idiomatic Introduction to the Imaginative World of Computational Thinking with Code, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.