【问题标题】:How to get items from a Ruby hash?如何从 Ruby 哈希中获取项目?
【发布时间】:2016-11-02 19:06:52
【问题描述】:

我从 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"},

我可以像这样记录导出链接:

logger.debug  file.export_links

但是,我无法获取文本/纯 url,尝试:

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

undefined method[]' for nil:NilClass` 出错。

如何在 @export_links 中获取 text/plain 的值?

【问题讨论】:

  • file.export_links.class 是什么?
  • @spickermann 返回 Hash 或 NilClass

标签: ruby-on-rails arrays ruby hash


【解决方案1】:

你在找这个吗?

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

或者

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

如果你需要第一场比赛。

【讨论】:

  • 第一个想法返回 private method select' 调用 nil:NilClass` 第二个 undefined method find' 调用 nil:NilClass`
  • 您的代码示例显示分配给@export_links。它应该包含哈希,但当你尝试这个想法时它是 nil。
猜你喜欢
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 2015-02-08
  • 1970-01-01
  • 1970-01-01
  • 2016-11-14
  • 2021-12-16
  • 1970-01-01
相关资源
最近更新 更多