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.

【Ruby】filter / detect / mapの違い

Posted at

##filter
要素に対して{}内が真であった要素を全て含む配列を返す
真になる要素がひとつもなかった場合は空の配列を返す

[1, 2, 3, 4, 5].filter { |num| num.even? }
# => [2, 4]

[1, 3, 5].filter { |num| num.even? }
# => []

##detect
要素に対してブロックを評価した値が真になった最初の要素を返す
真になる要素が見つからない場合はnilを返す

[1, 2, 3, 4, 5].detect { |num| num.even? }
# => 2

[1, 3, 5].detect { |num| num.even? }
# => nil

##map
各要素に対してブロックを評価した結果を全て含む配列を返す

 [1, 2, 3, 4, 5].map { |num| num.even? }
# => [false, true, false, true, false]

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