Loop statements in Ruby
Loop statements are used to execute a block of statements repeatedly until a given condition is true.
Ruby provides the following loop statements:
- while loop
- until loop
- for loop
1. while loop
The while loop executes a block of statements as long as the given condition is true.
Syntax:while condition
statements
end
Example: whiledemo.rb
i = 1
while i <= 5
puts i
i = i + 1
end
Output:
ruby whiledemo.rb
1
2
3
4
5
2. until loop
The until loop executes a block of statements until the given condition becomes true.
Syntax:until condition
statements
end
Example: untildemo.rb
i = 1
until i > 5
puts i
i = i + 1
end
Output:
ruby untildemo.rb
1
2
3
4
5
3. for loop
The for loop is used to repeat a block of statements for a sequence of values.
Syntax:for variable in sequence
statements
end
Example: fordemo.rb
for i in 1..5
puts i
end
Output:
ruby fordemo.rb
1
2
3
4
5