簡體   English   中英

如何遍歷哈希數組,然后在Ruby中使用迭代的哈希值填充新的哈希鍵

[英]How to iterate over array of hashes, then populate new hash keys using iterated hash values in Ruby

我有一個像這樣的數組:

result = [
  {:label=>:road, :value=>"carl-schurz str."},
  {:label=>:house_number, :value=>"25"},
  {:label=>:postcode, :value=>"36041"},
  {:label=>:city, :value=>"fulda"},
  {:label=>:state_district, :value=>"fulda kreis"}
] 

我想返回類似以下的哈希值:

output = {
  "road" => "carl-schurz str.",
  "house_number" => "25",
  "postcode" => "36041",
  "city" => "fulda",
  "state_district" => "fulda kreis"
}

因為我知道哈希也可以有位置,所以我一直在嘗試以下方法:

result.each do |r|
    r.each do |key, value|
      output[value[0]] = value[1]
    end
   end 

但是我沒有得到正確的結果。

只需添加一些其他解決方案就可以了。

我個人會做這樣的事情:

Hash[result.map { |h| [h[:label], h[:value]] }]

您可能要考慮的另一件事是each_with_object ,它對於構造新對象非常方便。 在這種情況下,它將類似於:

new_hash = result.each_with_object({}) do |h, r|
  r[h[:label]] = h[:value]
end

您可以使用“地圖”輕松完成此操作...

result.map { |h| [h[:label], h[:value]] }.to_h
Hash[result.map { |h| [h[:label], h[:value]] }]

甚至“減少” ...

result.reduce(Hash.new) { |h,o| h[o[:label]] = o[:value]; h }

這個簡單的基准顯示“減少”形式比其他形式稍快:

require 'benchmark'

result = [
  {:label=>:road, :value=>"carl-schurz str."},
  {:label=>:house_number, :value=>"25"},
  {:label=>:postcode, :value=>"36041"},
  {:label=>:city, :value=>"fulda"},
  {:label=>:state_district, :value=>"fulda kreis"}
] 

n = 1_000_000

Benchmark.bmbm do |x|
  x.report('Hash[]    ') { n.times { Hash[result.map { |h| [h[:label], h[:value]] }] } }
  x.report('map...to_h') { n.times { result.map { |h| [h[:label], h[:value]] }.to_h } }
  x.report('reduce    ') { n.times { result.reduce(Hash.new) { |h,o| h[o[:label]] = o[:value]; h } } }
end

#                  user     system      total        real
# Hash[]       1.830000   0.040000   1.870000 (  1.882664)
# map...to_h   1.760000   0.040000   1.800000 (  1.810998)
# reduce       1.590000   0.030000   1.620000 (  1.633808) *
result.map { |h| h.values_at(:label, :value) }.to_h
  #=> {:road=>"carl-schurz str.", :house_number=>"25", :postcode=>"36041", 
  #    :city=>"fulda", :state_district=>"fulda kreis"}

另一種方式:

result.map.with_object({}) { |h, new_h| new_h[h[:label]] = h[:value] }

我能夠使用以下方法獲得所需的結果:

result.each do |r|
  output[r.values[0]] = values[1]
end

知道使用hash_object.values是關鍵。

暫無
暫無

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

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