🐘
【Rails】ハッシュの配列をハッシュ化
概要
こういう配列を、
[
{ name: "Tanaka", age: 20, email: "tanaka.example.com" },
{ name: "Suzuki", age: 30, email: "suzuki.example.com" },
{ name: "Yamada", age: 40, email: "yamada.example.com" }
]
指定したキーの値でハッシュ化したいときに、Enumerable#index_by
を使うと便利。
[
{ name: "Tanaka", age: 20, email: "tanaka.example.com" },
{ name: "Suzuki", age: 30, email: "suzuki.example.com" },
{ name: "Yamada", age: 40, email: "yamada.example.com" }
].index_by(:name)
=>
{
"Tanaka" => { :name=>"Tanaka", :age=>20, :email=>"tanaka.example.com" },
"Suzuki" => { :name=>"Suzuki", :age=>30, :email=>"suzuki.example.com" },
"Yamada" => { :name=>"Yamada", :age=>40, :email=>"yamada.example.com" }
}
ただし、Rails のモジュールなので、 Ruby 単体では使えないことに注意。
環境
rails (7.0.8)
指定したキーを持っていない要素が存在するとき
nil をキーとしたハッシュができます。
[
{ name: "Tanaka", age: 20, email: "tanaka.example.com" },
{ name: "Suzuki", age: 30 },
{ name: "Yamada", age: 40, email: "yamada.example.com" }
].index_by { |user| user[:email]}
=>
{
"tanaka.example.com" => { :name=>"Tanaka", :age=>20, :email=>"tanaka.example.com" },
nil => { :name=>"Suzuki", :age=>30 },
"yamada.example.com" => { :name=>"Yamada", :age=>40, :email=>"yamada.example.com" }
}
インスタンスの配列にも使える
Article.all.index_by(&:title)
=>
{
"あああ"=> #<Article:0x0000ffff9cedab88 id: 1, title: "あああ", body: "body", is_published: false, created_at: Mon, 26 Feb 2024 00:52:53.492071000 UTC +00:00, updated_at: Mon, 26 Feb 2024 00:52:53.492546000 UTC +00:00>,
"いいい"=> #<Article:0x0000ffff9cedaa70 id: 2, title: "いいい", body: "body2", is_published: false, created_at: Mon, 26 Feb 2024 00:53:06.826336000 UTC +00:00, updated_at: Mon, 26 Feb 2024 00:53:06.826339000 UTC +00:00>,
"あああいいい"=> #<Article:0x0000ffff9ceda8e0 id: 3, title: "あああいいい", body: "body", is_published: false, created_at: Mon, 26 Feb 2024 00:53:06.826278000 UTC +00:00, updated_at: Mon, 26 Feb 2024 00:53:06.826329000 UTC +00:00>
}
Discussion