Project Ramon

A learning journey from a Ruby noob perspective

Working Arrays


I learned a couple of neat things in the Koans about_arrays recently, and thought it would be cool  to share.

The .slice method can be used to pick and chose elements out of an array or a range. Here is what the documentation says about .slice:


Lets entertain a couple of examples.

Take a slice out of Arrays

If we were to use the slice method on an array of ours here are some examples of what that could look like:

Like the documentation above states, the first argument in the .slice method is the index that .slice starts with while the second argument is the length from start. Line 4 in the example above starts at the index 0 or extreme_acts[0] and displays the next two indexes for a total length of 3 indexed values.

In an array, an index of negative one extreme_acts[-1] will always refer to the last element in an array. So if we said extreme_acts[-3], then we could use the knowledge of [-1] being the last element in our extreme_acts which holds the value of :venomous_serpent_tamer. Now to get to extreme_acts[-3] we simply count backwards in our array two more spaces, giving us the element :para_sailing. In this particular case extreme_acts[1] and extreme_acts[-3] are synonymous to one another.

Array Management: Push, Pop, Shift & Unshift

To add/remove an element from the end of an array we can use the methods .push and .pop respectively.


In the illustration above we added :soft_sunrizes to the extreme_acts array by using the .push method, adding :soft_sunrizes to our list. Since a soft sunrise is the most unlike value in our list, line 8 .pops removes :soft_sunrizes from our list. .pop is used to remove the last element of an array.

To add an element to the front of our extreme_acts array we see from our example below that extreme_acts now has :casual_stroll at the [0] index instead of the original :base_jumping. To remove :casual_stroll we use the .shift method, and can see from the illustration below that our extreme_acts array has returned to normal.


Slicing with Ranges

To slice an array using ranges we can substitute the typical parentheses ( ) and use brackets [ ]. Then we can slice out some elements from our extreme_acts array like so:


If you have enjoyed this post covering some Ruby basics, or have a critique to add. Consider leaving a comment, it will help other readers as well as myself grow one step at a time in comprehending some fundamental concepts.


Categories: AirPair, Newbie, Ruby

Tags: , ,

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