Looping Through Numbers
Part of the Fundamentals section of Coddy's Ruby journey — lesson 56 of 88.
Challenge
EasyIn 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:
- Read a number
nfrom input (this will be the upper limit) - Use a loop to iterate from 1 to
n - For each number in the range, call your
fizzbuzzmethod and print the result
Each result should be printed on a new line using puts.
For example, if the input is:
5The output should be:
1
2
Fizz
4
BuzzIf the input is:
15The output should be:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzTry 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
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False