Home > other >  Extracting Nested Hash-Array Values to Individual String Values
Extracting Nested Hash-Array Values to Individual String Values

Time:10-03

I'm trying to extract the values inside a nested hash with values inside an array within a hash value (basically a nested hash-array value) into individual string values. Hash value sample is below:

{"Video Analysis"=>{
"Video Width"=>["1920"],
"Video Height"=>["1080"],
"Video Framerate"=>["29.97"],
"Video Bitrate"=>["50000000"],
"Interlaced Video"=>["True"],
"Header Duration"=>["00:04:59:[email protected]"],
"Content Duration"=>["00:01:59:[email protected]"],
"Relative Gated Loudness"=>["-23.115095138549805"],
"True Peak Signal"=>["-5.3511543273925781"]}}

And the expected output shall be individual string values like this:

Video Width = 1920
Video Height = 1080...

I actually made a code but it gets larger as I extract each hash-array value individually

labels_hash = inputs['labels_hash'].select{ |k,v| k == 'Video Analysis'}.values.flatten
labels_subhash = vantage_labels_hash[0]

OTTVideoWidthArray = labels_subhash.select{ |k,v| k == 'Video Width'}.values.flatten
outputs['Video Width'] = OTTVideoWidthArray[0].to_f
OTTVideoHeightArray = labels_subhash.select{ |k,v| k == 'Video Height'}.values.flatten
outputs['Video Height'] = OTTVideoHeightArray[0].to_f

So I wanted to have something that is shorter to run. Hope you can help. Thanks!

CodePudding user response:

You can do this all at once:

some_hash = {
  'foobar' => { 
    'foo' => ['bar'], 
    'faz' => ['baz']
  }
}

foo, faz = nil # initialize as nil
some_hash['foobar'].each do |key, value|
  string = "#{key}: #{value.first}"
  if key == 'foo'
    foo = string
  elsif key == 'faz'
    faz = string
  [...]
  end
end

puts foo #=> "foo: bar"
puts bar #=> "faz: baz"
  • Related