With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required