## DEV Community

QUANON

Posted on • Updated on

# Lazy FizzBuzz

I though up this Fizz Buzz suddenly when I was about to go to the bathroom. So I made this note π

``````def genarate_lazy_list(number, yell)
[*Array.new(number - 1, nil), yell].cycle
end

numbers = 1.step.lazy
fizzes = genarate_lazy_list(3,'Fizz')
buzzes = genarate_lazy_list(5,'Buzz')
fizzbuzzes = genarate_lazy_list(15,'FizzBuzz')

# Add backslash for irb. I prefer leading dots to trailing ones.
numbers \
.zip(fizzes, buzzes, fizzbuzzes) \
.map { |n, fizz, buzz, fizzbuzz| fizzbuzz || buzz || fizz || n } \
.take(30) \
.each(&method(:puts))
``````
``````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
``````

## Top comments (7)

QUANON

I thought up more declarative one.

``````def say(fizzbuzz)
def fizzbuzz.for_multiples_of(number)
loop.lazy.flat_map { [*Array.new(number - 1, nil), self] }
end

fizzbuzz
end

fizzes = say('Fizz').for_multiples_of(3)
buzzes = say('Buzz').for_multiples_of(5)
``````

Seiei Miyagi • Edited

Awesome! zipping infinite generators is really coolπ

Tips: `Array#cycle` can be used to generate infinite sequence of Fizz and Buzz.

``````numbers = 1.step
fizzes = [nil, nil, "Fizz"].cycle
buzzes = [nil, nil, nil, nil, "Buzz"].cycle

numbers \
.lazy \
.zip(fizzes, buzzes) \
.map { |n, *yells| yells.any? ? yells.join : n } \
.take(30) \
.each(&method(:puts))
``````

QUANON

Thank you! The method makes it simpler πͺ

QUANON

Everybody who fizzes the buzzes misses that fizzbuzz entity is redundant:

You're right β¨ Thank you for your reply π

QUANON • Edited

Object#presence (in Active Support Core Extensions) makes it simpler π

``````require 'active_support'
require 'active_support/core_ext/object/blank'

numbers \
.zip(fizzes, buzzes) \
.map { |n, fizz, buzz| "#{fizz}#{buzz}".presence || n } \
.take(30) \
.each(&method(:puts))
``````