访问嵌套数组中的特定元素

时间:2017-12-05 01:43:30

标签: arrays json ruby hash

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

[  
  {
    "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"],但我知道这是错误的。

1 个答案:

答案 0 :(得分:2)

打印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"