Skip to content

Instantly share code, notes, and snippets.

@tgmerritt
Created August 19, 2015 14:30
Show Gist options
  • Save tgmerritt/453b81554158e3eea7f9 to your computer and use it in GitHub Desktop.
Save tgmerritt/453b81554158e3eea7f9 to your computer and use it in GitHub Desktop.
FizzBuzz One Line in Ruby - which is fastest?
#!/bin/ruby
require "benchmark"
iterations = 100_000
Benchmark.bm do |bm|
bm.report do
iterations.times do
(1..100).each{|i| (str = (i%3!=0 ? '':"Fizz")+(i%5!=0 ? '':"Buzz")).empty? ? i : str}
end
end
bm.report do
iterations.times do
(1..100).map { |i| (fb = [["Fizz"][i % 3], ["Buzz"][i % 5]].compact.join).empty? ? i : fb }
end
end
end
# user system total real
# 3.320000 0.040000 3.360000 ( 3.437508)
# 7.980000 0.090000 8.070000 ( 8.289550)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment