1

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!

1
  • If h is a variable that holds your hash I suggest simply h["Video Analysis"].transform_values(&:first) #=> {"Video Width"=>"1920", "Video Height"=>"1080",...,"True Peak Signal"=>"-5.3511543273925781"}. See Hash#transform_values. Commented Oct 2, 2022 at 18:22

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

3 Comments

but how can I print it into individual variables, like "Video Width: 1920"?
i mean i would just access them directly from the hash, kinda like you are already doing but i edited my answer. Its not exactly pretty either but maybe it helps
Already got the code working! Thanks Haumer for the big help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.