I learned a couple of neat things in the Koans about_arrays recently, and thought it would be cool to share.
.slice method can be used to pick and chose elements out of an array or a range. Here is what the documentation says about
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 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[-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
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
: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  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.