Fifth article in the Prepare for a Ruby job interview series. In this article, we’ll take a look at the main loops in the Ruby language.
While
As in most programming languages, While will repeat the block passed until the condition is met.
x = 0
while x < 100
p x
x +=1
end
p x +=1 while x < 100 # one-liner
Until
Opposite of While.
x = 0
until x > 50
p x
x +=1
end
p x +=1 until x > 50 # one-liner
Each
Each is the main loop that you’re probably using all the time as a Ruby developer.
[1, 2, 3].each do |i|
p i
end
For
Since each
is more widely adopted I don’t recommend using for, but here’s how to use it :
for i in [1, 2, 3] do
p i
end
Times
Times is a shortcut to run a block a defined number of times.
3.times { p 'yes' }
3.times { |i| p i }
Upto
Another useful shortcut to run a block through a range of number.
3.upto(5) { |i| p i }
Downto
Opposite of Upto.
5.downto(3) { |i| p i }
Redo
Will repeat the current iteration if the condition is met.
5.times do |i|
p i
redo if i == 4
end
# 0
# 1
# 2
# 3
# 4
# 4
# Infinite loop
Next
Go to the next iteration.
Break
Get out of the current loop before it’s too late!
Continue to the sixth part about Ruby Blocks : Procs and lambas.