如何更新每个嵌套哈希的值

时间:2014-11-13 06:56:55

标签: ruby

这是数组结构中的散列,

我想将split(',')应用于每个值并进行更新。

例如,原始值"176x144,320x256,640x512,960x768,1280x1024"是一个字符串,

更新后,[" 172x144",...,]应该是数组的字符串。

怎么做?

map(&:split(',')) ?

数据

=> [{"codec"=>"mjpeg",
  "resolutions"=>"176x144,320x256,640x512,960x768,1280x1024",
  "max_fps"=>"30,30,30,30,30",
  "vbr_max_bitrate"=>"40000000",
  "quant"=>"3",
  "qvalue"=>"50",
  "qpercent"=>"49",
  "cbr_policy"=>"framerate,imagequality",
  "cbr_max_bitrate"=>"2000000"},
 {"codec"=>"h264",
  "resolutions"=>"176x144,320x256,640x512,960x768,1280x1024",
  "max_fps"=>"30,30,30,30,30",
  "vbr_max_bitrate"=>"40000000",
  "quant"=>"99",
  "qvalue"=>"28",
  "qpercent"=>"45",
  "cbr_policy"=>"framerate,imagequality",
  "cbr_max_bitrate"=>"2000000"}]

1 个答案:

答案 0 :(得分:1)

这将创建一个包含所需值的哈希的新数组:

arr.map do |hash|
  Hash[hash.map { |k, v| [k, v.split(',')] }]
end
=> [{"codec"=>["mjpeg"], 
    "resolutions"=>["176x144", "320x256", "640x512", "960x768", "1280x1024"], 
    "max_fps"=>["30", "30", "30", "30", "30"], "vbr_max_bitrate"=>["40000000"], 
    "quant"=>["3"], "qvalue"=>["50"], "qpercent"=>["49"], 
    "cbr_policy"=>["framerate", "imagequality"], "cbr_max_bitrate"=>["2000000"]},
   {"codec"=>["h264"],
    "resolutions"=>["176x144", "320x256", "640x512", "960x768", "1280x1024"], 
    "max_fps"=>["30", "30", "30", "30", "30"], "vbr_max_bitrate"=>["40000000"], 
    "quant"=>["99"], "qvalue"=>["28"], "qpercent"=>["45"], 
    "cbr_policy"=>["framerate", "imagequality"], "cbr_max_bitrate"=>["2000000"]}]