0

I often find myself checking multiple conditions. How can I cut down on the number of lines used to achieve the same effect?

def super_fizzbuzz(array)
    final = []
    for num in array
        if num % 15 == 0
            final << 'FizzBuzz'
        elsif num % 5 == 0
            final << 'Buzz'
        elsif num % 3 == 0
            final << 'Fizz'
        else
            final << num
        end
    end
    final
end
Dylan Richards
  • 796
  • 3
  • 9
  • 26

6 Answers6

2
def super_fizzbuzz(array)
  array.map do |num|
    a = []
    a << 'Fizz' if num % 3 == 0
    a << 'Buzz' if num % 5 == 0
    a.empty? ? num : a.join()
  end
end
xdazz
  • 158,678
  • 38
  • 247
  • 274
1
def super_fizzbuzz(array)
  final = [] 
  array.each do |num|
    num % 15 == 0 ? final << 'FizzBuzz' : num % 5 == 0 ? final << 'Buzz' : num % 3 == 0 ? final << 'Fizz' : final << num
  end
  final
end

But your way is more readable.

zer0uno
  • 7,521
  • 13
  • 57
  • 86
1
def super_fizzbuzz(array)
  array.map do |num|
    case 0
    when num % 15 then "FizzBuzz"
    when num % 5 then "Buzz"
    when num % 3 then "Fizz"
    else num
    end
  end
end
sawa
  • 165,429
  • 45
  • 277
  • 381
1

This is slightly more complex, but reduces number of explicit coded conditionals to 2:

FIZZBUZZ = { 3 => 'Fizz', 5 => 'Buzz' }

def super_fizzbuzz(array)
  array.map do |num|
    fbs = FIZZBUZZ.select do |divisor,cat|
      num % divisor == 0
    end.values 
    fbs.empty? ? num : fbs.join
  end
end

There is always the danger when coding for DRY that you take things too far. In this case, with only two overlapping categories, I think the above is a little unwieldy. However, add another category or two:

FIZZBUZZ = { 3 => 'Fizz', 5 => 'Buzz',  7 => 'Boom', 11 => 'Whizz' }

and it starts to look smarter.

Neil Slater
  • 26,512
  • 6
  • 76
  • 94
1

Quote:

I think Fizz-Buzz is "hard" for some programmers because (#1) it doesn't fit into any of the patterns that were given to them in school assignments, and (#2) it isn't possible to directly and simply represent the necessary tests, without duplication, in just about any commonly-used modern programming language.

Source: c2.com Wiki

Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32
1

Another way:

def super_fizzbuzz(arr)
  arr.map do |e|
    s = ''
    s << 'Fizz' if (e%3).zero?
    s << 'Buzz' if (e%5).zero?
    s = e if s.empty?
    s
  end
end

super_fizzbuzz [9, 25, 225, 31]
  #=> ["Fizz", "Buzz", "FizzBuzz", 31]
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100