どうも、ちょげ(@chogetarou)です。
配列(array)の要素を条件で検索して取り出す方法を紹介します。
方法

配列(array)の要素を条件で検索して取り出す方法は、2つあります。
selectメソッド
ひとつは、selectメソッドを使う方法です。
まず、配列からselectメソッドを呼び出します。
selectメソッドのブロックで、取り出す要素の条件式を返します。
selectメソッドのブロック内では、引数で配列の要素を取得します。
#arr=対象の配列, condition=条件式
result = arr.select { |item| condition }
上記のselectメソッドは、条件式で配列内の要素を検索し、条件式でtrueを返したすべての要素を取り出します。
使用例
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = numbers.select { |item| item % 2 == 0}
p result
出力:
[2, 4, 6, 8]
detectメソッド
もうひとつは、detectメソッドを使う方法です。
まず、配列からdetectメソッドを呼び出します。
detectメソッドのブロックで、取り出す要素の条件式を返します。
detectメソッドのブロック内では、引数で配列の要素を取得します。
#arr=対象の配列, condition=条件式
result = arr.detect { |item| condition }
上記のdetectメソッドは、条件式で配列内の要素を検索し、条件式でtrueを返した最初の要素を取り出します。
使用例
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = numbers.detect { |item| item % 2 == 0}
p result
出力:
2
まとめ
配列(array)の要素を条件で検索して取り出す方法は、次の2つです。
- selectメソッドを使う方法
result = arr.select { |item| condition }
- detectメソッドを使う方法
result = arr.detect { |item| condition }
コメント