我需要幫助計算哈希陣列 "aoh "內的出現次數,并產生預期的輸出 "摘要"。
這是原始資料 "aoh":
aoh = [{:interface=>"1A" 。
:host=>"host_1"。
:status=>"online"}。
{:interface=>"1A",
:host=>"host_2"。
:status=>"online"}。
{:interface=>"1A",
:host=>"host_3"。
:status=>"offline"}。
{:interface=>"2A"。
:host=>"host_4"。
:status=>"offline"},
{:interface=>"2A"。
:host=>"host_5"。
:status=>"offline"}。
{:interface=>"2A"。
:host=>"host_6"。
:status=>"online"}.
]
這就是預期的結果
這就是預期的結果
summary = [{:interface=>"1A"/span>, : online_hosts=> 2, :offline_hosts=> 1},
{:interface=>"2A", : online_hosts=> 1, :offline_hosts=> 2}]
注意:我正在嘗試這段代碼......
summary = Hash. new { |h, k| h[k] = { online:/span> 0, offline:/span> 0 } }
aoh.each do |item|
summary[item[:interface]][item[:status] == 'online' ? :在線 : :離線] = 1 ]
end
摘要
=> {"1A"=>{:online=>2,: offline=>1}, "2A"/span>=>{: online=>1, :offline=>2}. # 差不多了,但這不是預期的結果。
這幾乎產生了預期的結果,但這種方式的介面值被移到了哈希之外作為一個鍵,并且哈希鍵的名稱也不是預期的。我確實需要在哈希中保留介面密鑰對。
uj5u.com熱心網友回復:
如果你試圖直接建立一個哈希值陣列,你必須在每次迭代中掃描陣列以找到介面的摘要。這是很尷尬的,也是很昂貴的。
建立哈希值的陣列。
構建哈希的哈希值更簡單、更快速。做你正在做的同樣的事情,但也要在摘要中存盤介面名稱。然后從產生的哈希值中取值。
# 同樣的事情,但也在值中存盤介面名稱。
summary = Hash.new do |h, k|
h[k] = { 介面: k, 在線: 0, 離線: 0 }
end }
# 同樣的事情,只是更容易閱讀。
aoh.each do|item|
status = item[:status] == 'line' ? :在線 : :離線 ?
summary[item[:interface]][status] = 1
end
# 你想要的是哈希的值。
p summary.values
uj5u.com熱心網友回復:
你可以使用Enumerable#group_by。
aoh.group_by { |h| h[:interface] }
.map do |k,a|
n = a.count { |h| h[:status] == "online" } { |h| h[:status] == "online"
{ interface: k, online_hosts: n, offline_hosts: a.size - n }
end
#=> [{:interface=> "1A", :online_hosts=>2, :offline_hosts=>1},
# {:interface=> "2A", :online_hosts=>1, :offline_hosts=>2}】
注意:
aoh.group_by { |h| h[:interface] }
#=> {"1A"=>[{:interface=> "1A", :host=> "host_1", :status=> "online"},/span>
# {:interface=> "1A", :host=> "host_2", :status=> "online"},
# {:interface=> "1A", :host=> "host_3", :status=> "offline"}】,
# "2A"=>[{:interface=> "2A", :host=> "host_4", :status=> "offline"},
# {:interface=> "2A", :host=> "host_5", :status=> "offline"},
# {:interface=> "2A", :host=> "host_6", :status=> "online"}]}
另一種方法是,在 "我 "與 "你 "之間進行選擇。
另一種方法是使用Hash#update(又稱merge!)的形式,它采用了一個塊來確定被合并的兩個哈希中存在的鍵的值。這里,該塊是do |_,o,n| ... end。三個區塊變數的定義見檔案,_,o和n。(_持有公共密鑰。我使用下劃線來表示該變數,以向讀者發出信號,表明它沒有被用于區塊計算,這是一個常見的慣例。
aoh.each_with_object({}) do |g,h|
h.update(
g[:interface]=>
{ interface: g[:interface] 。
online_hosts: g[:status] == "online" ? 1 : 0,
offline_hosts: g[:status] == "online" ? 0 : 1 ?
}
) do |_,o,n|
{ interface: o[:interface] 。
online_hosts: o[:online_hosts] n[:online_hosts] 。
offline_hosts: o[:offline_hosts] n[:offline_hosts].
}
end>
end.values
#=> [{:interface=> "1A", :online_hosts=>2, :offline_hosts=>1},
# {:interface=> "2A", :online_hosts=>1, :offline_hosts=>2}】
注意,Hash#values的接收器是:
{"1A"=>{:interface=>"1A">, : online_hosts=>2, :offline_hosts=> 1},
"2A"=>{:interface=>"2A">, : online_hosts=>1, :offline_hosts=> 2}}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323815.html
標籤:
