Ok so I'm trying to hash this out for practice. So my thought is that we could prevent an extra check from the num % 3 == 0 && num % 5 == 0
1 2 -Fizz 3 4 Buzz -Fizz 6 7 8 -Fizz 9 Buzz 11 -Fizz 12 13 14 FizzBuzz
With this attempt we are missing "Fizz" but get "Buzz" and "FizzBuzz". Any thought or ideas for a Ruby solution?
def fizzbuzz(num)
# if num % 3 == 0 && num % 5 == 0
# "FizzBuzz"
# Push the String "Fizz"/"Buzz"
result = ""
if num % 3 == 0
result << "Fizz"
end
if num % 5 == 0
result << "Buzz"
else
num
end
end
# Ruby creates these sequences using the ''..'' and ''...'' range operators.
# The two-dot form creates an inclusive range,
# while the three-dot form creates a range that excludes the specified high value.
def fizzbuzz_printer
(1..100).each do |num|
puts fizzbuzz(num)
end
end
fizzbuzz_printer
CodePudding user response:
A method in Ruby returns the value of its last expression unless you explicitly return.
Your last expression is:
if num % 5 == 0
result << "Buzz"
else
num
end
In this case, if the number is not divisible by 5, you just return num.
You likely want:
def fizzbuzz(num)
# if num % 3 == 0 && num % 5 == 0
# "FizzBuzz"
# Push the String "Fizz"/"Buzz"
result = ""
if num % 3 == 0
result << "Fizz"
end
if num % 5 == 0
result << "Buzz"
elsif !result.empty?
result
else
num
end
end
CodePudding user response:
Without num % 3 == 0 && num % 5 == 0 LOL:
def fizzbuzz(num)
if num % 15 == 0
"FizzBuzz"
elsif num % 3 == 0
"Fizz"
elsif num % 5 == 0
"Buzz"
else
num
end
end
Using presence from ActiveSupport:
def fizzbuzz(num)
result = ""
result << "Fizz" if num % 3 == 0
result << "Buzz" if num % 5 == 0
result.presence || num
end
(will work in rails, or in plain ruby with require 'active_support/core_ext/object/blank')
CodePudding user response:
A little archaic, but this would work:
def fizzbuzz(num)
(result ||= '') << "Fizz" if num % 3 == 0
(result ||= '') << "Buzz" if num % 5 == 0
result || num
end
The expression result ||= '' is a conditional assignment: if result has a truthy value, it just returns it, but if it is falsey (here: nil), it first assigns an empty string to it and then returns result.
On the first line the conditional assignment actually isn't needed because result can't have any value beside nil. You could just as well write result = 'Fizz' if num % 3 == 0 but I preferred to have that symmetry.
If you're working with frozen string literals, you can use '' instead of ''.
