Arrays in Ruby

This article serves as a kind of cheatsheet for ruby arrays. It assumes you know what an array is already.

  • As with everything in ruby, arrays are objects and therefore have methods
  • Arrays in ruby are stack-based (first in, last out)

Declare array literals like this;

   arr = [1,2,3,4,5]
   arr = []

Access array elements like this (zero based, as with other languages). Note that this will return “nil” if you go outside of the bounds of the array, it will not error;

   elem = arr[2]

Add something onto the array in one of these ways, it’ll be appended to the end (or, pushed onto the stack if you like);

   arr << 6
   arr.push 6

You can pop like this, remembering that this one line will both remove the last element from your array AND return it;

   elem = arr.pop

But you can also add to the start (or any place in the array you want) with the “insert” method, where argument 1 is the position and argument 2 is the value’. The below would insert an element at the start of the array (remember though, it will always be the last one that’s popped, not the most recently added);

   arr.insert 0,100

You can find the size of the array with one of the following, they are all exactly the same, I personally just pick whichever one sounds best in the context of the code (the “size” of employees doesn’t sound right, the “count” of employees does!);


Iterate through an array with the “each” method, which will give you the element in a code block;

array.each { |x| puts x }

And finally, you can sort an array with this method (exclamation mark intended, hey that’s ruby for you!);


The rest of this class is detailed over at


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s