Menu
Coddy logo textTech

Looping Through Numbers

Part of the Fundamentals section of Coddy's Ruby journey. Lesson 56 of 88.

challenge icon

Challenge

Easy

In the previous lesson, you created the fizzbuzz method that handles a single number. Now, add a loop to process a range of numbers from 1 to a given limit.

Modify your code to:

  1. Read a number n from input (this will be the upper limit)
  2. Use a loop to iterate from 1 to n
  3. For each number in the range, call your fizzbuzz method and print the result

Each result should be printed on a new line using puts.

For example, if the input is:

5

The output should be:

1
2
Fizz
4
Buzz

If the input is:

15

The output should be:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Try it yourself

# Read input
number = gets.chomp.to_i

# Method from previous lesson
def check_divisible(number, divisor)
  return number % divisor == 0
end

# Create the fizzbuzz method
def fizzbuzz(n)
  if check_divisible(n, 3) && check_divisible(n, 5)
    return "FizzBuzz"
  elsif check_divisible(n, 3)
    return "Fizz"
  elsif check_divisible(n, 5)
    return "Buzz"
  else
    return n.to_s
  end
end

# Call the fizzbuzz method and print the result
puts fizzbuzz(number)

All lessons in Fundamentals

Practice on your own: Online Ruby compiler