3 ms·
Indent your code with four spaces; that'll make it format properly. Your solution is pretty close, and honestly, is decent enough. There are some idiomatic sho
by cheald 15y ago
Indent your code with four spaces; that'll make it format properly.
Your solution is pretty close, and honestly, is decent enough. There are some idiomatic shortcuts you could take, though; ranges are objects and expose #each, you can use postfix conditionals, and you can use % instead of #modulo.
Here's how I'd do it.
(1..100).each do |i|
print i unless i % 3 == 0 or i % 5 == 0
print "Fizz" if i % 3 == 0
print "Buzz" if i % 5 == 0
print "\n"
end
(print is like puts, but doesn't append the newline, letting me construct the line piecewise).
This might actually run a wee bit slower than your solution, because all three conditions are evaluated per run, but it's less code and easier to read. Good lead-in to a discussion about code clarity vs optimization.