AnApprentice AnApprentice - 5 months ago 8
Ruby Question

How to get items from a ruby hash?

I have the following hash being returned from the Google Drive API:

@export_links=
{"application/rtf"=>
"https://docs.google.com/feeds/download/documents/export/Export?id=xxx&exportFormat=rtf",
"application/vnd.oasis.opendocument.text"=>
"https://docs.google.com/feeds/download/documents/export/Export?id=xxx&exportFormat=odt",
"text/html"=>
"https://docs.google.com/feeds/download/documents/export/Export?id=xxx&exportFormat=html",
"application/pdf"=>
"https://docs.google.com/feeds/download/documents/export/Export?id=xxx&exportFormat=pdf",
"application/zip"=>
"https://docs.google.com/feeds/download/documents/export/Export?id=xxx&exportFormat=zip",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"=>
"https://docs.google.com/feeds/download/documents/export/Export?id=xxxx&exportFormat=docx",
"text/plain"=>
"https://docs.google.com/feeds/download/documents/export/Export?id=xxx&exportFormat=txt"},


I'm able to log export links like so:

logger.debug file.export_links


However, I'm unable to get the text/plain url, trying:

logger.debug file.export_links["text/plain"]


This is erroring with
undefined method
[]' for nil:NilClass`.

How can I get the value for text/plain within @export_links?

Thanks

Answer

Are you looking for this?

@export_links.select { |k, v| v if k == 'text/plain' }

Or

@export_links.find { |k, _| k == 'text/plain' }

if you need the first match.