I would like a more elegant solution for this problem, I think the FizzBuzzArrayBuilder
class is not used properly. Also can those if
statements be removed somehow?
Any suggestion on how to improve this by still using OOP is welcome.
Problem:
Given the array [1, 2, 3, 4, ... 100]
, print all the elements as follows:
- if the element can be divided by 3 print:
Fizz
- if the element can be divided by 5 print:
Buzz
- if the element can be divided by both 3 and 5 print:
FizzBuzz
- else print the number
Output:
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz ...
Solution:
class Fizz
def output
puts 'Fizz'
end
end
class Buzz
def output
puts 'Buzz'
end
end
class FizzBuzz
def output
puts 'FizzBuzz'
end
end
class Element
def initialize(value)
@value = value
end
def output
puts @value
end
end
class FizzBuzzArrayBuilder
def initialize(array)
@array = array
end
def build
result = []
@array.each do |e|
if e % 15 == 0
result << FizzBuzz.new
elsif e % 3 == 0
result << Fizz.new
elsif e % 5 == 0
result << Buzz.new
else
result << Element.new(e)
end
end
result
end
end
class Counter
def initialize(array)
@fizz_buzz_array = FizzBuzzArrayBuilder.new(array).build
end
def output_array
@fizz_buzz_array.map(&:output)
end
end
array = (1..100).to_a
Counter.new(array).output_array