-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path04_arrays_and_hashes.rb
142 lines (80 loc) · 2.18 KB
/
04_arrays_and_hashes.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#1. ACCESSING AND ELEMENT FROM AN ARRAY
#Display first post only
posts = ["post1", "post2", "post3"]
puts posts[0]
# 2. ADDING AN ELEMENT TO AN ARRAY
#add a new post to my collection of posts
posts = ["post1", "post2", "post3"]
posts << "post4"
puts posts
or
posts = ["post1", "post2", "post3"]
posts.push("post4")
puts posts
# 3. DELETING AN ELEMENT FROM AN ARRAY
#deleting one of my posts
posts = ["post1", "post2", "post3"]
posts.delete_at(1)
puts posts
# 4. CREATING A HASH
#restaurant menu: dusplay the dishes + prices
restaurant_menu = {
"Pizza" => "10€",
"Pasta" => "12€",
"Steak" => "18€"
}
puts restaurant_menu
restaurant_menu = Hash.new
restaurant_menu["Fish"] = "15€"
restaurant_menu["Desert"] = "6€"
puts restaurant_menu
# 5. ACCESSING A KEY-VALUE PAIR FROM A HASH
# online menu -> display the price for a specific dish
restaurant_menu = {
"Pizza" => "10€",
"Pasta" => "12€",
"Steak" => "18€"
}
puts restaurant_menu["Pizza"]
# 6. ADDING A KEY-VALUE PAIR TO A HASH
# add a new dish + price to the menu
restaurant_menu = {
"Pizza" => "10€",
"Pasta" => "12€",
"Steak" => "18€"
}
restaurant_menu["Fish"]=["15€"]
puts restaurant_menu
# 7. DELETING A KEY-VALUE PAIR FROM A HASH
# removing a dish + price from the menu
restaurant_menu = {
"Pizza" => "10€",
"Pasta" => "12€",
"Steak" => "18€"
}
restaurant_menu.delete("Pizza")
puts restaurant_menu
# 8. ITERATING OVER AN ARRAY
#displaying the main ingredient for each of our recipes
recipes = ["Leek", "Carrot", "Shrimp"]
recipes.each do |ingredient|
puts "Main ingredient for this recipe: #{ingredient}"
end
# 9. ITERATING OVER A MULTIDIMENSIONAL ARRAY
#displaying main ingredients for main dishes and for deserts
recipes = [["Leek", "Carrot", "Shrimp"],["Apple", "Pear", "Cheese"]]
recipes.each do |sub_array|
sub_array.each do |ingredient|
puts "Main ingredient for this recipe: #{ingredient}"
end
end
# 10. ITERATING OVER A HASH
# display the dishes + prices in a customized way
restaurant_menu = {
"Pizza" => "10€",
"Pasta" => "12€",
"Steak" => "18€"
}
restaurant_menu.each do |meal, price|
puts "#{meal} price is #{price}"
end