O'Reilly logo

Learn Ruby the Hard Way: A Simple and Idiomatic Introduction to the Imaginative World of Computational Thinking with Code, Third Edition by Zed A. Shaw

Stay ahead with the world's most comprehensive technology and business learning platform.

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

Start Free Trial

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.

Start Free Trial

No credit card required