Last active
March 13, 2017 03:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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