Lesson 10 of 15

Loops

Loops in Ruby

while

Runs as long as a condition is true:

i = 1
while i <= 5
  puts i
  i += 1
end

until

The opposite of while — runs until the condition becomes true:

i = 1
until i > 5
  puts i
  i += 1
end

loop with break

loop runs forever; use break to exit:

i = 0
loop do
  i += 1
  break if i >= 5
end
puts i  # 5

times

The times method on integers is the most Ruby-idiomatic way to repeat something N times:

3.times { puts "hello" }

Your Task

Implement factorial(n) using a while loop. The factorial of n (written n!) is the product of all integers from 1 to n.

  • factorial(0) = 1
  • factorial(5) = 120

Print factorial(5) and factorial(10).

ruby.wasm loading...
Loading...
Click "Run" to execute your code.