0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby】FizzBuzz問題

Last updated at Posted at 2020-09-15

内容

1~100までの数字をターミナルに出力し、3の倍数の時は数字の代わりに文字列でFizz、5の倍数の時はBuzz、両方の倍数である15の倍数の時はFizzBuzzと出力されるプログラムを作ってねという問題について解説を載せて書いてみる。

答え

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

解説

変数numに1を代入し、whileメソッドでnumが100以下の時、3の倍数かつ5の倍数の時にFizzBuzzと出力。3の倍数の時にFizzと出力。5の倍数の時Buzzと出力。それ以外はnumを出力し、最後にnumに1を追加する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?