【问题标题】:Accessing specific elements in nested array访问嵌套数组中的特定元素
【发布时间】:2018-05-18 14:12:51
【问题描述】:

我正在尝试访问这个哈希数组:

[  
  {
    "Book": "1: SS",
    "Concordance": ". they tugged and heaved at the door, but it 
    wouldn’tbudge, not even when hermione tried her alohomora charm, now 
    what? said ron, these birds … they can’t be here just for decoration,",
    "Position": 82471,
    "Spell": "alohomora"
  },
  {
    "Book": "1: SS",
    "Concordance": "oh, move over, hermione snarled, she grabbed Harry’s 
    wand, tapped the lock, and whispered, alohomora! the lock clicked and 
    the door swung open — they piled through it, shut it quickly,",
    "Position": 47346,
    "Spell": "alohomora"
  },
  {
    "Book": "1: SS",
    "Concordance": "it on snape if he showed any sign of wanting to hurt 
    Harry, now, don’t forget, it’s locomotormortis, hermione muttered as 
     ron slipped his wand up his sleeve, i know, ron snapped, don’t",
    "Position": 65427,
    "Spell": "locomotormortis"
  },
]

如何访问第二个数组元素中的Spell?如何访问该数组的特定字段?

我尝试过Mentions.data[1]["Spell"],但我知道这是错误的。

【问题讨论】:

  • 嗯,这就是您通常访问任何数组的方式。
  • “我知道这是错误的”不是一个足够精确的错误描述,我们无法帮助您。 什么错了? 怎么错了?你怎么知道?什么不起作用?它怎么行不通?你的代码有什么问题?您收到错误消息吗?错误信息是什么?你得到的结果不是你期望的结果吗?你期望什么结果,为什么,你得到的结果是什么,两者有什么不同?您正在观察的行为不是期望的行为吗?期望的行为是什么,为什么,观察到的行为是什么,它们有何不同?

标签: arrays json ruby hash


【解决方案1】:

打印 Mentions.data[1] 以查看 Ruby 看到的内容。

{:Book => "1: SS",
 :Concordance => 
  "oh, move over, hermione snarled, she grabbed Harry’s \n" +
  "    wand, tapped the lock, and whispered, alohomora! the lock clicked and \n" +
  "    the door swung open — they piled through it, shut it quickly,",
 :Position => 47346,
 :Spell => "alohomora"}

那么很明显我们使用了:

Mentions.data[1][:Spell] #=> "alohomora"

【讨论】:

  • 谢谢!然而 irb 在输入第二个代码建议时返回 nil。
  • Mentions.data[1] 返回什么?
猜你喜欢
  • 1970-01-01
  • 2020-07-15
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-16
  • 2021-07-09
  • 1970-01-01
相关资源
最近更新 更多