Cover by Michael Fitzgerald

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

O'Reilly logo

Chapter 6. Arrays

The Array class is one of Ruby's built-in classes. Arrays are compact, ordered collections of objects. Ruby arrays can hold objects such as String, Integer, Fixnum, Hash, Symbol, even other Array objects—you name it. Any object that Ruby can create, it can hold in an array.

Each element in an array is associated with and referred to by an index (also known as a subscript in other languages). Array elements are automatically indexed (numbered) with an integer (Fixnum), starting with 0, then numbered consecutively, adding 1 for each additional element. In certain instances, you can refer to the last element of an array with −1, the second to last with −2, and so forth. That's handy.

Ruby arrays are not as rigid as arrays in other languages. In static, compiled programming languages, you have to guess the ultimate size of the array at the time it is created. If an array grows beyond that size, you must copy the array into a temporary one and then create a new, larger array, copying the temporary array into it. Ruby is a dynamic language—as are Perl, Python, and PHP, among others—and therefore lets you grow an array at will, adding elements while it automatically increases the size. Another interesting distinction is that Ruby can hold arrays with objects of all different types, not just one type, as is common in static languages. You'll see this in action later in this chapter.

Remember that, by convention, any Ruby method that ends with an exclamation point (!), like ...

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