Data Structures Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Creating Arrays

A

set variable name = [element 1, element 2, …]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Access Array Elements by Index

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Multidimensional Arrays

A

An array of arrays

multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

MD Array Example

A

my_2d_array = [[1,1,1],[2,2,2],[3,3,3]]

my_2d_array.each do |array|
print “#{array}\n”
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Hashes

Create hash with literal notation

A
A hash is a collection of key-value pairs
hash = {
  key1 => value1,
  key2 => value2,
  key3 => value3
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Create Hash with Hash.new

A

pets = Hash.new
pets[“Stevie”] = “cat”
Adds the key “Stevie” with the value “cat” to the hash

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Iterating Over Multidimensional Arrays

A

s = [[“ham”, “swiss”], [“turkey”, “cheddar”], [“roast beef”, “gruyere”]]

s.each do |sub_array|
  sub_array.each do |food|
    puts food
  end
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Iterating Over Hashes

A
restaurant_menu = {
  "noodles" => 4,
  "soup" => 3,
  "salad" => 2
}
restaurant_menu.each do |food, price|
  puts "#{food}: #{price}"
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly