-2

Can someone please explain why the following code does not work properly? It only returns "fizzbuzz" 100 times as the answer. Thank you.

def fizzbuzz(number)
  idx = 0
  while idx <= number
    num = number[idx]
    if num % 3 == 0 && num % 5 == 0
      puts 'fizzbuzz'
    elsif num % 5 == 0
      puts 'buzz'
    elsif num % 3 == 0
      puts 'fizz'
    else 
      puts num
    end
    idx += 1
  end
end

fizzbuzz(100)
cdlane
  • 40,441
  • 5
  • 32
  • 81
Asfand
  • 1
  • 4

1 Answers1

1

You have two issues here:

  1. num = number[idx]
  2. The idx variable is the one that should be used for your checks not num:

    def fizzbuzz(number)
      idx = 0
      while idx <= number
        if idx % 3 == 0 && idx % 5 == 0
          puts 'fizzbuzz'
        elsif idx % 5 == 0
          puts 'buzz'
        elsif idx % 3 == 0
          puts 'fizz'
        else 
          puts idx
        end
        idx += 1
      end
    end
    
    fizzbuzz(100)
    

The above is your solution.

The reason it is always printing 'fizzbuzz', no matter what number you pass to the fizzbuzz method, is because you are assigning number[idx] to the a local variable num where you should be using the idx counter in your conditional statements.

You need to print the numbers from 1 to the number you pass to fizzbuzz. For multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. For numbers which are multiples of both 3 and 5 print “FizzBuzz".

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Cyzanfar
  • 6,997
  • 9
  • 43
  • 81