ruby 将嵌套散列数组值提取为单个字符串值

l7wslrjt  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(117)

我尝试将嵌套哈希值中的值与哈希值中的数组中的值(基本上是嵌套哈希数组值)提取到单个字符串值中。哈希值示例如下:

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

预期输出应为如下所示的单个字符串值:

Video Width = 1920
Video Height = 1080...

我实际上做了一个代码,但是当我单独提取每个哈希数组值时,代码会变得更大

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

所以我想有一些更短的运行。希望你能帮助。谢谢!

slsn1g29

slsn1g291#

您可以一次完成所有操作:

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"

相关问题