4 ms·
I passed with this : class FizzBuzz def self.run for i in (1..100) if((i.modulo(3)==0) && (i.modulo(5)==0)) puts "FizzBuzz" elsif(i.
by lowglow 15y ago
I passed with this :
class FizzBuzz
def self.run
for i in (1..100)
if((i.modulo(3)==0) && (i.modulo(5)==0))
puts "FizzBuzz"
elsif(i.modulo(3)==0)
puts "Fizz"
elsif (i.modulo(5)==0)
puts "Buzz"
else
puts i
end
end
end
end
and got this :
"Nice job, you beat the FizzBuzz test! If you believe in the rumors, you are officially better than 99.5% of programmers."
--
I'm new to ruby, is there any way to "optimize" that code?
-
Edit : I don't know how to format code for HN.
- TamDenholm 15y agohttp://news.ycombinator.com/formatdoc http://news.ycombinator.com/formatdoc
- lowglow 15y agocool, thanks. :)
- cheald 15y agoIndent 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.