# [RAILS] [Ruby] Tonight, I tried to summarize the loop processing [times, break ...]

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.

# Simplified chart

### Iterative processing

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

# Methods / grammars that change the number of repetitions

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

### Simple loop

``````
num = 0

5.times do
p num
end
``````

#### `Return value`

``````
0
0
0
0
0
=> 5
``````

### Loop while changing the value

``````
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
``````

# Techniques during loop processing

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
``````