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 1 year has passed since last update.

いいコード悪いコードまとめ7章 コレクション〜ネストを解消する構造化技法〜

Posted at

標準ライブラリに同じような機能のメソッドはないか

実は便利なメソッドがあったのに存在を知らずに自分で書いてしまった!なんてことは誰しも経験したことがあるのではないでしょうか。そうならないためにも、一度調べてみてから、なければ自分で書く癖をつけたいですねー。

早期nextで条件分岐のネストを解消できないか

例えば、以下のように多重分岐している場合、これは早期nextで解消できるかもしれません。

number = 5

if number == 1
  puts "number is 1"
elsif number == 2
  puts "number is 2"
elsif number == 3
  puts "number is 3"
elsif number == 4
  puts "number is 4"
elsif number == 5
  puts "number is 5"
end

以下のように書くとスッキリですね。

number = 5

next if number == 1
next if number == 2
next if number == 3
next if number == 4
puts "number is 5"

早期breakで条件分岐のネストを解消できないか

これも先ほどと同じですが、

number = 5

if number == 1
  puts "number is 1"
  break
elsif number == 2
  puts "number is 2"
  break
elsif number == 3
  puts "number is 3"
  break
elsif number == 4
  puts "number is 4"
  break
elsif number == 5
  puts "number is 5"
end

以下のように書き換えると可読性が上がりますね。

number = 5

break if number == 1
break if number == 2
break if number == 3
break if number == 4
puts "number is 5"
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?