我現在在一家公司實習,我有一個資料庫,我連接到該資料庫以獲取有關我們客戶的一些特定資料。查詢已全部完成,資料庫正在回傳我需要的資料,但現在我需要弄清楚如何將資料合并為必要的格式。我們使用 Ruby 3.1.2 作為參考。
這是我從我們的資料庫中收到的格式(真實資料會大得多,所以我只使用一個小資料集,直到邏輯可靠)。
[{ "product_id"=>1, "customer_id"=>001 },
{ "product_id"=>2, "customer_id"=>001 },
{ "product_id"=>1, "customer_id"=>002 },
{ "product_id"=>3, "customer_id"=>002 },
{ "product_id"=>1, "customer_id"=>003 },
{ "product_id"=>2, "customer_id"=>003 },
{ "product_id"=>3, "customer_id"=>003 }]
當我獲得這些資料時,我需要獲取每個不同的“customer_id”串列以及他們分配給它們的每個“product_id”的串列。我需要回到下面的示例。
{001=>[1, 2], 002=>[1, 3], 003=>[1, 2, 3]}
我以為我有下面一行的解決方案,但它似乎沒有按我的預期作業。
data.group_by(&:customer_id).transform_values { |p| p.pluck(:product_id) }
uj5u.com熱心網友回復:
除了#group_by可以#each_with_object用來迭代地構建所需的散列。
data.each_with_object({}) { |x, h|
h[x["customer_id"]] ||= []
h[x["customer_id"]] << x["product_id"]
}
# => {1=>[1, 2], 2=>[1, 3], 3=>[1, 2, 3]}
uj5u.com熱心網友回復:
我會這樣做:
array = [{ "product_id"=>1, "customer_id"=>001 },
{ "product_id"=>2, "customer_id"=>001 },
{ "product_id"=>1, "customer_id"=>002 },
{ "product_id"=>3, "customer_id"=>002 },
{ "product_id"=>1, "customer_id"=>003 },
{ "product_id"=>2, "customer_id"=>003 },
{ "product_id"=>3, "customer_id"=>003 }]
array.group_by { |hash| hash['customer_id'] }
.transform_values { |values| values.map { |value| value['product_id'] } }
#=> { 1 => [1, 2], 2 => [1, 3], 3 => [1, 2, 3] }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/516600.html
標籤:轨道上的红宝石红宝石
上一篇:基本ruby??if陳述句的問題
