Data Structures Flashcards
Creating Arrays
set variable name = [element 1, element 2, …]
Access Array Elements by Index
Each array element is assigned an index number, starting with zero [0]. Access each element with array name and index number in brackets:
array | 5 | 7 | 9 | 2 | 0 |
index 0 1 2 3 4
array_name = [5, 7, 9, 2, 0]
print array_name[2]
=> 2
Multidimensional Arrays
An array of arrays
multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
MD Array Example
my_2d_array = [[1,1,1],[2,2,2],[3,3,3]]
my_2d_array.each do |array|
print “#{array}\n”
end
Hashes
Create hash with literal notation
A hash is a collection of key-value pairs hash = { key1 => value1, key2 => value2, key3 => value3 }
Create Hash with Hash.new
pets = Hash.new
pets[“Stevie”] = “cat”
Adds the key “Stevie” with the value “cat” to the hash
Iterating Over Multidimensional Arrays
s = [[“ham”, “swiss”], [“turkey”, “cheddar”], [“roast beef”, “gruyere”]]
s.each do |sub_array| sub_array.each do |food| puts food end end
Iterating Over Hashes
restaurant_menu = { "noodles" => 4, "soup" => 3, "salad" => 2 } restaurant_menu.each do |food, price| puts "#{food}: #{price}" end