简体   繁体   中英

How do I access a hash value that only exists in 1 attribute out of many?

So this one is a bit tricky.

I have an attribute that looks like this:

[22] pry(main)> n.media.meta_info[:response][:outputs]
=> [{"id"=>486,
  "url"=>"http://some-video.com/by-fire.mp4",
  "label"=>"webmp4",
  "state"=>"finished",
  "format"=>"mpeg4",
  "type"=>"standard",
  "frame_rate"=>30.06,
 {"id"=>488848287,
  "url"=>"http://some-video.com/by-fire.webm",
  "label"=>"webwebm",
  "state"=>"finished",
  "format"=>"webm",
  "type"=>"standard",
  "frame_rate"=>30.06,
 {"id"=>488848288,
  "url"=>"http://some-video.com/by-fire.ogv",
  "label"=>"webogv",
  "state"=>"finished",
  "format"=>"ogg",
  "type"=>"standard",
  "frame_rate"=>30.059,
 {"id"=>488848289,
  "url"=>
   "https://zencoder-temp-storage-us-east-1.s3.amazonaws.com/",
  "label"=>nil,
  "state"=>"finished",
  "format"=>"mpeg4",
  "type"=>"standard",
  "frame_rate"=>30.06,
  "thumbnails"=>
   [{"label"=>nil,
     "images"=>
      [{"dimensions"=>"56x100",
        "file_size_bytes"=>15142,
        "format"=>"PNG",
        "url"=>"https://some-video.s3.amazonaws.com/uploads/video/video_file/id/by-fire.png"}]}],
  "md5_checksum"=>nil}]

I am trying to access the thumbnails info, specifically the URL for the thumbnails.

I can't figure out how to get there though.

When I try to go the nested hash key of thumbnails it doesn't work:

[23] pry(main)> n.media.meta_info[:response][:outputs][:thumbnails]
TypeError: no implicit conversion of Symbol into Integer
from (pry):22:in `[]'

Thoughts?

The [{ at the beginning of the output indicates that an array is returned. You first need to find a element in the array that contains a thumbnails key:

outputs = n.media.meta_info[:response][:outputs]
output_with_thumbnail = outputs.find { |elem| elem.keys.include?('thumbnails') }

Then continue like this:

output_with_thumbnail['thumbnails']

如果您只是想查找缩略图,而不关心其余的输出,则可以这样使用#find

thumbnails = n.media.meta_info[:response][:outputs].find {|it| it[:thumbnails] }[:thumbnails]

您有一组哈希, thumbnails在第3个中:

n.media.meta_info[:response][:outputs][3][:thumbnails]

It looks like

outputs = n.media.meta_info[:response][:outputs]

is an Array of hashes. So, you need to iterate over them first:

outputs.each do |output|
  # deal with each output here
end

You can check for :thumbnails like so:

if (thumbnails = output[:thumbnails])
  # we've got thumbnails, deal with it here
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM