Skip to content

Instantly share code, notes, and snippets.

@kmayer
Last active March 13, 2017 03:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmayer/7631059 to your computer and use it in GitHub Desktop.
Save kmayer/7631059 to your computer and use it in GitHub Desktop.
FizzBuzz to 100 in one line of (very compact) ruby. And other variants
# How to use and experiment
# $ irb -I. -rfizzbuzz
# => fb = FizzBuzz.new
# => fb.enumerator_with_array_indices.take(30) == FizzBuzz.EXPECTATIONS
# => true
class FizzBuzz
EXPECTATIONS=[1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz"]
def shortest # 100 chars of ruby
Enumerator.new{|y|i=1;loop{y<<((s=[["Fizz"][i%3],["Buzz"][i%5]].compact.join).empty? ? i : s);i+=1}}
end
def enumerator_with_array_indices
Enumerator.new do |y|
i = 1
loop do
str = [["Fizz"][i%3],["Buzz"][i%5]].compact.join
y << )str.empty? ? i : str)
i += 1
end
end
end
def enumerator_with_cycles
Enumerator.new do |y|
i, fizz, buzz = 1, [nil,nil,"Fizz"].cycle, [nil,nil,nil,nil,"Buzz"].cycle
loop do
s = [fizz.next, buzz.next].compact.join
y << (s.empty? ? i : s)
i+=1
end
end
end
def enumerator_with_fetch
Enumerator.new{|y|i=1;loop{y<<{0=>"FizzBuzz"}.fetch(i%15,{0=>"Fizz"}.fetch(i%3,{0=>"Buzz"}.fetch(i%5,i)));i+=1}}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment