Adding The Twist
Part of the Fundamentals section of Coddy's Ruby journey — lesson 57 of 88.
Challenge
EasyIn the previous lesson, you created a FizzBuzz program that loops through numbers using the default divisors 3 and 5. Now, add the twist by making the divisors customizable through default parameters.
Modify your fizzbuzz method to accept three arguments:
n- the number to check (required)fizz_divisor- the divisor for "Fizz" (optional, defaults to3)buzz_divisor- the divisor for "Buzz" (optional, defaults to5)
The method should use these custom divisors instead of hardcoded values when checking divisibility.
You will receive three lines of input:
- The upper limit
n - The fizz divisor
- The buzz divisor
Loop from 1 to n and call your updated fizzbuzz method with all three arguments. Print each result.
For example, if the inputs are:
10
2
3The output should be:
1
Fizz
Buzz
Fizz
5
FizzBuzz
7
Fizz
Buzz
FizzIf the inputs are:
15
3
5The output should be:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzTry it yourself
# Read input
n = 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
# Loop through numbers from 1 to n and print the result
(1..n).each do |i|
puts fizzbuzz(i)
endAll 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