Ruby for Programmers – Part 6: Arrays

Oh boy, it’s been over a year since I updated this?! :(

We’re going to very quickly amp this up and get started on the real project.

Now that we’ve learned about blocks, it’s now time to learn about Arrays.

The basic Array works the way you expect:

It just stores, in order, the object you put into it. Since anything is an Object, you can even put classes inside of it.

Arrays have lots of useful functions, most of them involve blocks.

The catch with arrays is that, since everything is just pass by pointer, keep in mind the difference between modifying an array, and making a new one:

Notice how the second time function1 ran, it’s modified. array changed because the insert command modified it. This is more weird when you consider some functions copy rather than modify:

Notice how it has the same output as before? This is because Array#compact returns a new array versus modifying it. There is, in fact, an Array#compact! function that will modify rather than copy. This is important for two reasons: 1) You may want to ensure that things get copies rather than modifying the original. Or 2) You way want to modify only the original to use less memory.

As a side note, an Array is an Enumerable module (we’ll go over modules soon) so there’s two places to look for things you can do to an array:

Array specific functions
Enumerable functions

Enumerable is just a placeholder for things over anything that enumerates. An array has it’s contents, but there are other things that are also enumerable. For example, Ranges, which we introduced earlier is an Enumerable too:

And one last note for Arrays: unlike some languages which guess which type, Arrays in Ruby are only 0-first integer buckets of contiguous length. You can easily waste memory like this:

If you want to have a dictionary or associative array, look no further than the Hash (on Part 7).