检查“nil”并设置它是否在哈希中“尝试”

时间:2015-03-14 06:32:23

标签: ruby

我想:

{
  "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

1 个答案:

答案 0 :(得分:2)

你可以写:

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