SoFunction
Updated on 2025-04-07

Introduction to the loop statement of the Ruby simple tutorial

Loop structure is indispensable in programming languages, so loops in Ruby also have their own custom rules.

When we focus on the loop structure, we need to know two factors: 1) the loop conditions; 2) the content of loop execution

Ruby has some ways to implement loop structures:

1. times method

As mentioned earlier, the syntax is as follows:

Copy the codeThe code is as follows:

Number of loops.times do                                                                                                                           �
Repeated actions                                                                                                                             �
end                                               }

#You can also add variables in the times module

{ |i|
    print "This is the", i+1, " time. \n"
}

# i variable is calculated from 0

2. for statement

Copy the codeThe code is as follows:

grammar:
for variable in start value.. end value do
Repeated actions
end

# do can be omitted

from = 0
to = 20
sum = 0
for i in from..to
   sum += 1
end

grammar:
for variables in object
Repeated actions
end

names = ["Windy", "Cindy", "Jack", "Hugo"]
for name in names
   print name, " likes Ruby. \n"
end


The second syntax for statement is very similar to the for each statement in java, for (i in list?) {...}

3. while statement

While statements are similar to those in JAVA

Copy the codeThe code is as follows:

grammar:
while condition do
Repeated actions
end

a = 1
sum = 0
while a < 10 do
   sum += a
   i += a
end

4. until statement
The syntax is similar to that of a while statement, but the loop will be repeatedly executed only when the conditions do not match.

Copy the codeThe code is as follows:

grammar:
until condition do
Repeated actions
end
# do can be omitted

sum = 0
until sum > 50
   sum += 1
end
print sum

# The above until loop can be converted into the following while loop
while !(sum > 50)
   sum += 1
end

5. Each method
I have mentioned this method before, here I will briefly record the syntax

Copy the codeThe code is as follows:

Object.each { |Variables |

Actions that you want to perform repeatedly

}

6. Loop method

It is a method without end conditions, just keeps looping, the example is as follows:

Copy the codeThe code is as follows:

loop {
   print "Ruby"
}

Loop control:

There are mainly the following keywords: break, next, redo; and in java, there are break, continue, return

Order use
break Stop the action and jump out of the loop immediately
next Jump directly to the next loop
redo Re-execute this loop with the same conditions


Summary: When the number of times is fixed, it is better to use the times method, while and each method can be used for most other loops.