Search code examples
rubyconditional-statementsfizzbuzz

FizzBuzz in Ruby with without 3 && 5


Ok so I'm trying to hash this out for practice. So my thought is that we could prevent an extra check from the num % 3 == 0 && num % 5 == 0

1 2 -Fizz +3 4 Buzz -Fizz +6 7 8 -Fizz +9 Buzz 11 -Fizz +12 13 14 FizzBuzz

With this attempt we are missing "Fizz" but get "Buzz" and "FizzBuzz". Any thought or ideas for a Ruby solution?

def fizzbuzz(num)
  # if num % 3 == 0 && num % 5 == 0
  #   "FizzBuzz"
  # Push the String "Fizz"/"Buzz"
  result = ""
  if num % 3 == 0
    result << "Fizz"
  end
  if num % 5 == 0
    result << "Buzz"
  else
    num
  end
end

# Ruby creates these sequences using the ''..'' and ''...'' range operators. 
# The two-dot form creates an inclusive range, 
# while the three-dot form creates a range that excludes the specified high value.

def fizzbuzz_printer
  (1..100).each do |num|
    puts fizzbuzz(num)
  end
end

fizzbuzz_printer

Solution

  • A method in Ruby returns the value of its last expression unless you explicitly return.

    Your last expression is:

      if num % 5 == 0
        result << "Buzz"
      else
        num
      end
    

    In this case, if the number is not divisible by 5, you just return num.

    You likely want:

    def fizzbuzz(num)
      # if num % 3 == 0 && num % 5 == 0
      #   "FizzBuzz"
      # Push the String "Fizz"/"Buzz"
      result = ""
      if num % 3 == 0
        result << "Fizz"
      end
      if num % 5 == 0
        result << "Buzz"
      elsif !result.empty?
        result
      else
        num
      end
    end