user3675188
user3675188

Reputation: 7419

How to update every nested hash's value

This is a hashed in an array struct,

I want to apply split(',') to every value and update it.

For example, the original value "176x144,320x256,640x512,960x768,1280x1024" is a string,

After updating, ["172x144", ...,] it should be and strings of an array.

How to do it ?

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

data

=> [{"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"}]

Upvotes: 0

Views: 32

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37419

This will create a new array with hashes with the values you need:

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"]}]

Upvotes: 1

Related Questions