Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Ruby Collections!
You have completed Ruby Collections!
So far while working with arrays, we've learned how to add and access the items inside. Now it's time to learn how to remove items in arrays.
Code Samples
Let's assume we have the following array:
array = ["milk", "eggs", "bread", "ice cream", "carrots", "potatoes"]
To access and remove the last item in the array, we can use the pop method:
last_item = array.pop
The last_item variable will now contain the string potatoes. The array now looks like this:
["milk", "eggs", "bread", "ice cream", "carrots"]
To access and remove the first item in the array, we use the shift method:
first_item = array.shift
The first_item variable now contains the string milk. The array now looks like this:
[ "eggs", "bread", "ice cream", "carrots" ]
We can use the drop method to take out a number of items from an array. The drop method's argument is the number of items to remove from the front of the array.
ice_cream_carrots = array.drop(2)
Similar to the unshift method, which adds to the beginning of an array, the shift method removes from the beginning of an array:
item = array.shift
The item variable now contains the string "eggs" and our array looks like this:
[ "bread", "ice cream", "carrots" ]
Let's add "potatoes" to the end of our array:
array.push("potatoes")
The array now contains:
["bread", "ice cream", "carrots", "potatoes"]
The slice method takes two arguments and removes and returns items from the array. The first argument is the index in the array, and the second argument is the number of items:
first_three_items = array.slice(0, 3)
Now, the first_three_items variable contains the following array:
["bread", "ice cream", "carrots"]
The array variable is now a single element:
["potatoes"]
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up