# [Ruby] [Ruby] I tried to summarize the loop processing tonight [times, break…]

Last time introduced the iterative processing due to the array. This time, the arrangement is also correct. Let’s focus on loop processing that is also used for range objects and so on.

# Simplified chart

### iteration

Method / Grammar Repeat Count
for ~ in ~ statement For elements of object
while statement While the specified condition is true
until statement While the specified condition is false
times method arbitrarily specified
loop method infinity

Grammar Function
next skip
redo Redo
break break

# Methods that change the number of iterations / Grammar

## for ~ in ~

Repeat for the number of elements (range)

``````
for num in 1..5 do
p num
end
``````

#### ` return value`

``````
1
2
3
Four
Five
=> 1..5
``````

## while

Repeat until the condition becomes 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 becomes true

``````
num = 16

until num <= 12 do
p num
num -= 2
end
``````

#### ` return value`

``````
16
14
=> nil
``````

## times

Repeat a 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
Four
=> 5
``````

## loop

repeat endlessly unless stopped with break

``````
num = 0

loop do
p num
num += 1
if num >= 3
break
end
end
``````

#### ` return value`

``````
0
1
2
=> nil
``````

# Technique 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
Four
Five
=> 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
Four
Five
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
``````

Tags:

Updated: