检查"nil"并在哈希中设置是否为"try"



我想要:

{
  "CATTLE" => {"Heifers" => 647, "Cows" => 633, "Weaners" => 662, "Steers" => 653},
  "BULL" => {"Bulls" => 196},
  "SHEEP" => {"Rams" => 410, "Ewes" => 1629, "Wethers" => 1579, "Calves" => 1241, "Weaners" => 300}
}

为了得到它,我从一个空的mobs = {}哈希开始,然后在循环时填充它。如果密钥是 nil ,我设置它,然后填充它。我想知道是否有更好的方法可以如下所示:

mob_livestock_group_response.each do |livestock_group|
  mobs[livestock_group['assetType']] = {} unless mobs[livestock_group['assetType']]
  mobs[livestock_group['assetType']][livestock_group['subtype']] = 0 unless mobs[livestock_group['assetType']][livestock_group['subtype']]
  mobs[livestock_group['assetType']][livestock_group['subtype']] += livestock_group['size']
end
你可以

这样写:

mob_livestock_group_response.each do |livestock_group|
  mobs[livestock_group['assetType']] ||= {}
  mobs[livestock_group['assetType']][livestock_group['subtype']] ||= 0
  mobs[livestock_group['assetType']][livestock_group['subtype']] += livestock_group['size']
end

此外,我会这样写:

mob_livestock_group_response.each do |livestock_group|
  type = livestock_group['assetType']
  sub  = livestock_group['subtype']
  size = livestock_group['size']
  mobs[type]      ||= {}
  mobs[type][sub] ||= 0
  mobs[type][sub] += size
end

相关内容

最新更新