Loop structures are essential in programming languages, so loops in Ruby have their own custom rules.
And we are concerned about the structure of the cycle, we need to know two factors: 1 The condition of the loop; 2 the contents of the loop execution
Ruby has some ways to implement the loop structure:
1. Times method
As mentioned above, the syntax is as follows:
Number of cycles.
Repeated actions performed repeatedly
End}
#也可以在times模块中加入变量
5.times {|i|
print ' This is ', i+1, ' time. \ n "
}
# I variables are calculated starting from 0.
2. For statement
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 variable in object
Repeated actions
End
names = ["Windy", "Cindy", "Jack", "Hugo"]
For name in Names
Print name, "likes Ruby." \ n "
End
The For statement for the second syntax is very similar to the for every statement in Java, for (I-in list?) {...}
3. While statement
While statements are also classes in Java
Grammar:
While condition do
Repeated actions
End
A = 1
sum = 0
While a < ten do
Sum + = A
i + A
End
4. Until statement
The syntax is similar to the while statement, but loops are executed repeatedly only if the condition does not match
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 to the while loop below
While! (Sum > 50)
sum = 1
End
5. Each method
This method has been mentioned before, here is a brief record of the syntax
Object. Each {| variable |
Actions that you want to perform repeatedly
}
6. Loop method
It is a method that does not have an end condition, but is continually looping through the following example:
Loop control:
There are mainly the following keywords: break,next,redo; in Java, there are Break,continue,return
Command |
Use |
Break |
Stop the action, jump out of the loop immediately |
Next |
Skip directly to the next loop |
Redo |
Re-execute this cycle with the same conditions |
Summary: When times are fixed, it is better to use the time method, while most other loops can use the while and each method almost.