7
3

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.

はじめての記事投稿

【Ruby】配列から偶数だけ抽出して新たな配列を作る方法は?

Last updated at Posted at 2023-06-15

学習の備忘録として残します。:pray:

方法①Rubyコード

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = numbers.select { |num| num.even? }
puts even_numbers

出力結果

[2, 4, 6, 8, 10]

上記のコードでは、
selectメソッドを使用して配列から偶数だけを抽出。
selectメソッドは、ブロック内の条件式が真になる要素だけを含む新しい配列を返す。
   ↓
条件式num.even?は、要素が偶数かどうかを判定するために使用。
選択された偶数だけの配列が生成され、それを今回はeven_numbersに代入。
   ↓
even_numbersを出力。

方法② Ruby コード

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.filter { |n| n.even? }

出力結果

[2, 4, 6, 8, 10]
7
3
1

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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?