Last time introduced iterative processing related to arrays. This time, the array is also good. Let's focus on the loop processing that is also used for range objects, etc.
Method/grammar | Number of repetitions |
---|---|
for ~ in ~Sentence | Element of object |
while statement | While the specified condition is true |
until statement | While the specified condition is false |
times method | Arbitrarily specified |
loop method | infinite |
grammar | function |
---|---|
next | skip |
redo | Redo |
break | Suspension |
for ~ in ~ Repeat for each element (range)
for num in 1..5 do
p num
end
Return value
1
2
3
4
5
=> 1..5
while Repeat until the condition is false
num = 0
while num <= 12 do
p num
num += 3
end
Return value
0
3
6
9
12
=> nil
until Repeat until the condition is true
num = 16
until num <= 12 do
p num
num -= 2
end
Return value
16
14
=> nil
times Repeat the specified number of times
num = 0
5.times do
p num
end
Return value
0
0
0
0
0
=> 5
num = 0
5.times do |num|
p num
num += 1
end
Return value
0
1
2
3
4
=> 5
loop Repeat indefinitely unless you stop with break
num = 0
loop do
p num
num += 1
if num >= 3
break
end
end
Return value
0
1
2
=> nil
next Can be skipped
num = 0..5
6.times do |num|
next if num == 1
p num
end
Return value
0
2
3
4
5
=> 6
redo Can be redone
num = 0..5
6.times do |num|
num += 1
p num
redo if num == 1
end
Return value
1
2
2
3
4
5
6
=> 6
break Can be interrupted
num = 0..5
6.times do |num|
break if num == 3
p num
end
Return value
0
1
2
=> nil
Recommended Posts