-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy path03_looping.rb
185 lines (115 loc) · 1.88 KB
/
03_looping.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#1. WHILE LOOP
number = 1
while number < 11
puts number
number = number + 1
end
=begin
Real world example: music player loop
while user does not press stop
get the next song
play that song
end
=end
#2. UNTIL LOOP
number = 1
until number == 11
puts number
number = number + 1
end
=begin
Real world example: music player loop
until user presses stop
get the next song
play that song
end
=end
#3. FOR LOOP
for num in 1...10
puts num
end
puts "--------------"
for num in 1..10
puts num
end
=begin
Real world example: music player loop
for songs 1..7
play song
end
=end
#4. NEXT
for number in 1..5
next if number % 2 == 0
puts number
end
=begin
Real world example: music player loop
for songs 1..10
next if song is more than 5 minutes long
end
=end
#5. LOOP METHOD
puts "Simple loop - an infinite loop!"
number = 0
loop do
number += 1
puts number
end
puts "Controlling the loop execution"
number = 0
loop do
number += 1
puts number
break if number == 5
end
# Real world example: music player loop
# loop do
#play songs on playlist
# stop playing (break!) when you reach song #7
# end
6. EACH METHOD
number.each do |x|
puts "Displaying number: #{x}"
end
#ANOTHER SYNTAX FOR THIS:
number.each { |x|
puts "Displaying number: #{x}"
}
=begin
Real world example: posts on a blog
posts.each do |post|
display title + first paragraph
end
=end
#7. TIMES METHOD
3.times do
puts "You've scored!"
end
puts "----------"
#SAME AS
counter = 0
loop do
counter +=1
puts "Testing loop do"
break if counter == 3
end
puts "----------"
#SAME AS
counter = 0
while counter <= 2
counter +=1
puts "Testing while loop"
end
puts "----------"
# SAME AS
counter = 0
until counter == 3
counter = counter + 1
puts "Testing until counter"
end
puts "----------"
# SAME AS
for num in 1..3
puts "Testing for loop"
end