Full Stack Founder · a live cohort for developersjoin the waitlist →
← Back to Blog
interviewThibault “Tibo” Denizet

Overview of loops in Ruby

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 .

$ whoami

Tibo, creator of Devmystify

Tibo

Hi, I'm the creator of Devmystify and author of Modular Rails and Master Ruby Web APIs.

I built a 6-figure consulting business while living in Thailand and now share practical advice on turning dev skills into a business: consulting, digital products, and SaaS.

join the cohort waitlist →

Comments

Loading comments...

> one email a week, real numbers

The other half of the job

You can already build. The free ebook answers the rest: which business is right for you, the real numbers behind each path, and the ladder to climb without quitting your job.

join 2,700+ developers · unsubscribe anytime · no spam, only receipts

Overview of loops in Ruby | Devmystify