[Ruby] FizzBuzz problem

Contents

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.

answer

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

Commentary

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

[Ruby] FizzBuzz problem
[Ruby] FizzBuzz problem
FizzBuzz problem
Ruby problem ⑦
ruby search problem
ruby API problem
[Ruby] Ruby API problem
ruby API problem
Explanation of the FizzBuzz problem
Let's solve the FizzBuzz problem!
I tried the FizzBuzz problem
[Ruby] problem with if statement
Ruby deposit system, algorithm problem
[Note] About the Fizz_Buzz problem (How Ruby on Rails works)
Ruby: I made a FizzBuzz program!
Calendar creation problem (fun Ruby practice problem)
A memorandum of the FizzBuzz problem
Expression used in the fizz_buzz problem
[Ruby] Search problem using index method
This problem is soberly difficult ... (Ruby)
Ruby learning 4
I tried a calendar problem in Ruby
[Ruby] Array
Implement FizzBuzz problem in test-driven development (preparation)
Ruby basics
Ruby learning 5
Ruby basics
Ruby Review 2
Ruby addition
Refactoring Ruby
Ruby learning 3
FizzBuzz various
Ruby setting 2
Ruby learning 2
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
Ruby settings 1
Refactoring Ruby
Ruby basics
Ruby memo
Ruby learning 1
[Problem] Weather on consecutive holidays (Ruby edition)
Ruby Review 1
[Ruby] Module
[Competition Pro] Solve the knapsack problem with Ruby
[Beginner's point of view] I tried to solve the FizzBuzz problem "easily" with Ruby!