FizzBuzz is a renowned coding challenge, often utilized in job interviews to gauge a candidate’s grasp of basic programming concepts. While simple in its essence, FizzBuzz is a perfect exercise for understanding loops and conditionals, especially in Ruby, a language known for its elegance and readability.
Understanding the FizzBuzz algorithm
The FizzBuzz algorithm involves iterating through numbers (usually from 1 to 100) and applying specific rules:
- Print “Fizz” for numbers divisible by 3.
- Print “Buzz” for numbers divisible by 5.
- Print “FizzBuzz” for numbers divisible by both 3 and 5.
- Print the number itself in all other cases.
The logic behind FizzBuzz
- Iteration: Looping through a series of numbers, which is typically done using Ruby’s
each
method. - Conditionals: Applying
if
statements to determine whether the current number meets certain divisibility criteria. - Output: Printing “Fizz”, “Buzz”, “FizzBuzz”, or the number based on the criteria met.
Implementing FizzBuzz in Ruby
Here’s how you can implement the FizzBuzz algorithm in Ruby:
(1..100).each do |i|
if i % 3 == 0 && i % 5 == 0
puts "FizzBuzz"
elsif i % 3 == 0
puts "Fizz"
elsif i % 5 == 0
puts "Buzz"
else
puts i
end
end
Breaking down the code
(1..100).each do |i|
: Iterates over numbers from 1 to 100. Each number is referred to asi
.if i % 3 == 0 && i % 5 == 0
: Checks ifi
is divisible by both 3 and 5.elsif i % 3 == 0
: Checks ifi
is divisible by 3.elsif i % 5 == 0
: Checks ifi
is divisible by 5.puts i
: Prints the number itself if none of the above conditions are met.end
: Ends the conditional and loop blocks.
Testing the algorithm
To test the algorithm, run this Ruby script in a suitable environment. You’ll observe that for numbers like 3 and 6, “Fizz” is printed, for 5 and 10, “Buzz” is printed, for numbers like 15 and 30, “FizzBuzz” is printed, and for other numbers like 1, 2, and 4, the number itself is printed.
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
.
.
.
Get more useful articles on Ruby