Lesson 3 of 8 · 7 min

Loops and ranges

Ruby has loops, but you will mostly use methods that repeat instead:

3.times { puts "Hello" }            # Hello, three times

1.upto(5) { |i| puts i }            # 1 2 3 4 5
10.downto(8) { |i| puts i }         # 10 9 8
(1..5).each { |i| puts i * i }      # 1 4 9 16 25

The part in curly braces is a block: a chunk of code passed to the method, which runs it as many times as it needs. |i| names the value the method hands to the block on each run.

For longer blocks, use do ... end:

(1..3).each do |round|
  puts "Round #{round}"
  puts "Fight!"
end

Ranges

1..5 includes 5. 1...5 (three dots) stops before 5. Ranges work with letters too: ('a'..'e').to_a gives ["a", "b", "c", "d", "e"].

while

The classic loop exists too, for when you do not know how many rounds you need:

savings = 0
savings += 15 while savings < 100

Your task

  1. Print Hip hip hooray! three times using times.
  2. Write factorial(n): 1 × 2 × ... × n (and factorial(0) is 1).
  3. Write fizzbuzz(n): returns "FizzBuzz" if n divides by 15, "Fizz" if by 3, "Buzz" if by 5, otherwise the number as text (n.to_s).

A method is defined with def name(params) ... end; the value of its last line is returned.

main.rb
# 1. three cheers


def factorial(n)
end

def fizzbuzz(n)
end

puts (1..15).map { |n| fizzbuzz(n) }.join(" ")

Ruby 3.4 runs right here in your browser. The first run downloads about 16 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…