Data Structures Flashcards
What is an array index?
Each element in the array has what’s called an index. The first element is at index 0, the next is at index 1, the following is at index 2, and so on.
How do you access an object in an array with the index?
With brackets
array = [5, 7, 9, 2, 0]
array[2]
# returns “9”, since “9”
# is at index 2
What are multidimensional arrays?
It’s an array of arrays
What are hashes?
A hash is a collection of key-value pairs
How do you create a hash?
You use the Hash.new method.
by setting a variable to Hash.new
my_hash = Hash.new
How do you add objects to a hash?
We add object to hash with bracket notation:
pets = Hash.new pets["Stevie"] = "cat"
How do you accesses objects in a hash?
We accesses it by using the same method like an array:
puts pets[“Stevie”]
pets = { "Stevie" => "cat", "Bowser" => "hamster", "Kevin Sorbo" => "fish" }
puts pets[“Stevie”]
What do we call it when we loop over a hash or an array?
We call it that we iterate over the hash or array.
How do we iterate over arrays?
We use the .each method
numbers = [1, 2, 3, 4, 5]
numbers.each { |element| puts element }
How do you iterate over multidimensional arrays?
s.each do | sub_array | sub_array.each do | y | puts y end end
How do you iterate over a hash?
As same as in a Array, nbut you need to have two arguments instead of one.
restaurant_menu.each do | item, price |
puts “#{item}: #{price}”
end