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?

Rubyの`flat_map`を段階的に理解する

0
Posted at

Rubyのflat_mapは、複雑なデータ構造をシンプルに扱える強力なメソッドです。
この記事では実務風のデータを使って、「元データ → 処理 → 処理後データ」の3ステップで解説します。


レベル1:元データ(grouped_data

まずは、グループごとにユーザー情報が格納されたハッシュ構造のデータです。

grouped_data = {
  "team_alpha" => [
    { name: "Alice", active: true,  status: :pending },
    { name: "Bob",   active: false, status: :confirmed }
  ],
  "team_beta" => [
    { name: "Carol", active: true,  status: :confirmed },
    { name: "Dave",  active: true,  status: :pending }
  ]
}

構造の特徴
• 各キー(チーム名)に複数のユーザーデータ(ハッシュ)が格納されている
• ネスト構造(ハッシュ → 配列 → ハッシュ)


レベル2:処理(flat_mapによる抽出と整形)

次に、条件に合うユーザーだけを抽出し、不要なnil値を除去します。

filtered_data = grouped_data.flat_map do |_team, members|
  members
    .select { |user| user[:active] && user[:status] != :confirmed }
    .map(&:compact)
end

処理のポイント
• selectで「activeかつ未承認」のユーザーだけを抽出
• map(&:compact)でnilを含むキーを除去(この例では影響なし)
• flat_mapにより、すべてのチームの結果を一つの配列に統合


レベル3:処理後データ(filtered_data)

最終的に得られるのは、条件に合うユーザーだけを集めたフラットな配列です。

[
  { name: "Alice", active: true, status: :pending },
  { name: "Dave",  active: true, status: :pending }
]

結果の特徴
• ネストが解消され、一次元の配列になる
• 条件に合うユーザーのみが残る
• データ整形済みで扱いやすい


flat_mapの魅力まとめ

•	抽出・整形・統合を一度に行える
•	ネストした配列を簡潔にフラット化できる
•	コード量を減らし、可読性を高められる

おわりに

flat_mapは、複数の配列を扱う場面で「抽出・整形・統合」を一括でこなせる頼れるメソッドです。
今回のように段階的に見ていくことで、その便利さと使いどころがより明確になります。
ぜひあなたのコードにも取り入れてみてください!

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?