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 5 years have passed since last update.

リファクタリング練習

Posted at

リファクタリング

リファクタリングは単にコードを読みやすくするだけではない
チーム開発において見やすいコードとは非常に重要で、チーム開発では他人のコードを解読する時間は非常に多くなる
その時間を短くすることは開発効率の促進に繋がる

array = [1, 2, 3, 4, 5].map do |el| 
  if el.odd?
    el 
  end
end.compact!

このプログラムは配列に格納されている数字から奇数のみを取り出すプログラムです。
これをワンライナーで書き直します。

array = [1, 2, 3, 4, 5].map { |el| el if el.odd? }.compact!
array = (1..5).to_a.delete_if { |el| el.even? }
array = (1..5).to_a.delete_if(&:even?)
array = [1, 2, 3, 4, 5].select{ |el| el.odd?}

mapメソッドは配列から値を一つずつ取り出して変数に格納するメソッド
odd?は奇数を判別するメソッド
delete_ifは条件に合わない値を削除するメソッド
to_aメソッドは対象を配列としてまとめて返すメソッド
even?は偶数を判別するメソッド

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?