簡體   English   中英

Ruby 數組 arrays 到 hash 以第一項為鍵

[英]Ruby array of arrays to hash with first item as key

我有以下形式的 arrays 數組(“pluck”使用的結果):

arr = [[1, 'A1', 'B1'],[2, 'A2', 'B2'],[3, 'A3', 'B3']]

如何從中獲得關注 hash ?

{1=>[1, 'A1', 'B1'], 2=>[2, 'A2', 'B2'], 3=>[3, 'A3', 'B3']}

我知道這種形式,但肯定也有一種線形式

hash = Hash.new

arr.each do |x|
  hash[x[0]] = x
end

輸入

arr = [[1, 'A1', 'B1'],[2, 'A2', 'B2'],[3, 'A3', 'B3']]

代碼

p arr.map{|a|[a.first,a]}.to_h

Output

{1=>[1, "A1", "B1"], 2=>[2, "A2", "B2"], 3=>[3, "A3", "B3"]}

我能想到的方法很少。

使用group_by(我個人選擇這個),reduce和inject方式。

arr = [[1, 'A1', 'B1'],[2, 'A2', 'B2'],[3, 'A3', 'B3']]

arr.reduce({}) { |result, record| result.merge!(record.first => record) }

Or 

arr.inject({}) { |result, record| result.merge!(record.first => record) }

OR

arr.group_by(&:first) # Short and sweet, I think you will pick this up.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM