1
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.

FizzBuzz問題のリファクタリング【Ruby】

Last updated at Posted at 2020-03-21

修正ポイント

  • if文のネストをなくす
  • 条件が当てはまる確率が低い方から先に記述
  • while分をeachメソッドに変更
  • 変数の数を減らす
  • コードを減らす

リファクタリング前

def fizzBuzz(count)
  i = 1
  while i < count + 1 do
    if i % 3 == 0 then
      if i % 5 == 0 then
        puts 'FizzBuzz'
      else
        puts 'Fizz'
      end
    elsif  i % 5 == 0 then
      puts 'Buzz'
    else
      puts i
    end
    i += 1
  end
end

fizzBuzz(20)

リファクタリング後

def fizzBuzz(count)
  (1..count).each do |c|
    if    c % 15 == 0
      puts 'FizzBuzz'
    elsif c %  5 == 0
      puts 'Buzz'
    elsif c %  3 == 0
      puts 'Fizz'
    else
      puts c
    end
  end
end

fizzBuzz(20)
1
0
4

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
1
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?