Dylan Richards
Dylan Richards

Reputation: 786

How can I DRY this series of conditional statements?

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

Upvotes: 0

Views: 145

Answers (6)

Cary Swoveland
Cary Swoveland

Reputation: 110755

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]

Upvotes: 1

Kimmo Lehto
Kimmo Lehto

Reputation: 6041

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

Upvotes: 1

Neil Slater
Neil Slater

Reputation: 27227

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.

Upvotes: 1

sawa
sawa

Reputation: 168269

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

Upvotes: 1

zer0uno
zer0uno

Reputation: 8030

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.

Upvotes: 1

xdazz
xdazz

Reputation: 160963

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

Upvotes: 2

Related Questions