Accessing Items in Arrays4:42 with Jason Seifer
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.
Index: The numbered position of an item in an array. Arrays all start with the first item having an index of 0.
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
Access the second item in the array (index 1):
Print out the first item in the array using the first method:
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:
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
You need to sign up for Treehouse in order to download course files.Sign up