Arrays

An array, or list, is very much like a string in some ways: It is a container whose elements can be referred to by their position and whose elements can be examined and changed using the same techniques you have just learned. But there is a big difference between the two. An array can hold objects of any type, not just characters.

Instead of the quotation marks that you use to create a string, surround a new array with square brackets. Elements of an array are separated by commas.

veggies = ["corn", "carrots"]
small_primes = [2, 3, 5, 7, 11]
some_objects = ["a string", 44, self]

How would you find the second element of the veggies array? Knowing what you know about string objects, you should be able to guess. (Remember, we start counting ...

Get Sams Teach Yourself Ruby in 21 Days 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.