Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Now that we've seen how to create arrays and add items to them, we're going to learn how to work with existing arrays and access what's inside them.
Terms
Index: The numbered position of an item in an array. Arrays all start with the first item having an index of 0.
Code Samples
Starting with the following array:
array = ["milk", "eggs", "bread", "ice cream", "pie", "potatoes"]
Access "milk", which is at the first position in the array (index 0), and assign it to a variable named "item":
item = array[0]
Access the second item in the array (index 1):
array[1]
Print out the first item in the array using the first method:
puts array.first
Print out the last item in the array, using the negative index and also the "last" method:
puts array[-1]
puts array.last
The fetch method can be used with an index to return that item in an array:
puts array.fetch(2) # => "bread"
If a second argument is provided to the fetch method and there is no corresponding item in the array, the second argument will be used as a default:
puts array.fetch(20, "cake") # => "cake"
Return the number of items in an array:
array.length
array.count
Return the number of items in the array matching what you send in:
array.count("eggs") # => 1
To find out if an array contains a particular item, use the include? method with the argument of the desired item:
array.include?("eggs") # => true
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