【发布时间】:2011-12-12 19:07:37
【问题描述】:
假设我正在从 API 取回 JSON 嵌套哈希(或哈希数组)
@example = {"results" = > {{"poop" => "shoop"},{"foo" => {"shizz" => "fizz", "nizzle"=>"bizzle"}}}
上面嵌套哈希的 YAML 标记
- poop: shoop
- foo:
shizz: fizz
nizzle: bizzle
现在让我们从散列中使用 ActiveRecord 创建一个数据库条目。这很好用。
Thing.create!(:poop => @example["results"]["poop"],
:shizz => @example["results"]["foo"]["shizz"],
:nizzle=> @example["results"]["foo"]["nizzle"])
但如果 'foo' 为空或 nil 怎么办?例如,如果 API 结果有一个带有 "first name","last name" # 等的 "person" 哈希,则 "person " 如果没有数据,hash 通常会为空,也就是说里面的 hash 不存在。
@example = {"results" = > {{"poop" => "shoop"},{"foo" => nil }}
Thing.create!(:poop => @example["results"]["poop"],
:shizz => @example["results"]["foo"]["shizz"],
:nizzle=> @example["results"]["foo"]["nizzle"])
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
处理此问题的最佳方法是什么?
【问题讨论】:
标签: ruby hash error-handling hash-of-hashes