A number from 1 to 100 is output to the terminal, and when it is a multiple of 3, it is output as Fizz as a character string instead of a number, when it is a multiple of 5, it is output as Buzz, and when it is a multiple of both, it is output as FizzBuzz. I will write a commentary on the problem of making a program.
def fizz_buzz
  num = 1
  while (num <= 100) do
    if (num % 3 == 0) && (num % 5 == 0)
      puts "FizzBuzz"
    elsif (num % 3) == 0
      puts "Fizz"
    elsif (num % 5) == 0
      puts "Buzz"
    else
      puts num
    end
    num = num + 1
  end
end
fizz_buzz
Assign 1 to the variable num, and output FizzBuzz when num is 100 or less in the while method, and when it is a multiple of 3 and a multiple of 5. Output as Fizz when it is a multiple of 3. Buzz and output when it is a multiple of 5. Otherwise, it outputs num and adds 1 to num at the end.
Recommended Posts