Ruby 配列の絞り込み:select・reject・find の使い方

スポンサーリンク

Ruby 配列の絞り込み:select・reject・find の使い方

配列から「条件に合う要素だけ取り出す」には selectrejectfind などを使います。


早わかりまとめ

メソッド 戻り値 向いている用途
select / filter 配列 条件に合う要素をすべて取り出す
reject 配列 条件に合わない要素をすべて取り出す
find / detect 要素 or nil 条件に合う最初の要素を1つ取り出す
find_index インデックス or nil 条件に合う最初の要素の位置を調べる
any? boolean 1つでも条件を満たすか確認する
all? boolean すべて条件を満たすか確認する
none? boolean 条件を満たす要素がないか確認する
include? boolean 特定の値が含まれるか確認する
count 整数 条件に合う要素数を数える

select / filter:条件に合う要素をすべて取り出す

numbers = [1, 2, 3, 4, 5, 6]

# 偶数だけ取り出す
evens = numbers.select { |n| n.even? }
p evens # [2, 4, 6]

# 3より大きい数
big = numbers.select { |n| n > 3 }
p big # [4, 5, 6]

オブジェクトの配列でよく使います。

users = [
  { name: 'Alice', active: true },
  { name: 'Bob', active: false },
  { name: 'Carol', active: true },
]

active_users = users.select { |user| user[:active] }
# [{ name: 'Alice', ... }, { name: 'Carol', ... }]

filterselect の別名です。


reject:条件に合わない要素を取り出す

numbers = [1, 2, 3, 4, 5, 6]

# 偶数を除く(= 奇数だけ)
odds = numbers.reject { |n| n.even? }
p odds # [1, 3, 5]

select の逆と考えると分かりやすいです。


find / detect:最初の1件を取り出す

users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Carol' },
]

user = users.find { |u| u[:id] == 2 }
p user # { id: 2, name: 'Bob' }

条件に合う要素がない場合は nil を返します。

result = users.find { |u| u[:id] == 99 }
p result # nil

detectfind の別名です。


find_index:インデックスで位置を調べる

fruits = ['apple', 'banana', 'cherry']

index = fruits.find_index { |f| f == 'banana' }
p index # 1

# 見つからない場合は nil
p fruits.find_index { |f| f == 'grape' } # nil

any? / all? / none?:条件確認

scores = [40, 55, 70, 80]

# 60点以上が1つでもあるか
p scores.any? { |s| s >= 60 }  # true

# 全員が60点以上か
p scores.all? { |s| s >= 60 }  # false

# 100点がいないか
p scores.none? { |s| s == 100 } # true

include?:特定の値が含まれるか

colors = ['red', 'green', 'blue']

p colors.include?('green')  # true
p colors.include?('yellow') # false

オブジェクトの配列には any? を使います。

users.include?({ id: 1, name: 'Alice' }) # 参照比較のため期待通りに動かないことがある
users.any? { |u| u[:id] == 1 }           # こちらを使う

count:条件に合う要素数を数える

numbers = [1, 2, 3, 4, 5, 6]

p numbers.count { |n| n.even? } # 3
p numbers.count                  # 6(全件)

まとめ

したいこと 使うもの
条件に合う要素をすべて取り出す select / filter
条件に合わない要素を取り出す reject
条件に合う最初の要素を1つ取り出す find / detect
条件に合う要素の位置を調べる find_index
1つでも条件を満たすか確認する any?
すべて条件を満たすか確認する all?
条件を満たす要素がないか確認する none?
特定の値が含まれるか確認する include?

配列の繰り返し処理は「Ruby の繰り返し処理:each・times・map の使い分け」を参照してください。