以嵌套哈希方式访问数据

时间:2012-12-15 14:36:30

标签: ruby-on-rails-3 json

首先,我在这里使用这个gemfile:

https://github.com/ryanwkan/covetous

初始化后

my_profile = Covetous :: Profile :: Career.new'rwk#1242'

我得到一个像这样的数组

http://pastebin.com/CcW0aaLL

当我尝试像这样访问它时

my_profile.heroes,它返回

[{"name"=>"Ziyi", "id"=>10692899, "level"=>60, "hardcore"=>false, "paragonLevel"=>87, "gender"=>1, "dead"=>false, "class"=>"wizard", "last-updated"=>1354337248}, {"name"=>"Aerendil", "id"=>5987778, "level"=>60, "hardcore"=>false, "paragonLevel"=>0, "gender"=>1, "dead"=>false, "class"=>"demon-hunter", "last-updated"=>1353389408}, {"name"=>"Bubba", "id"=>9177617, "level"=>60, "hardcore"=>false, "paragonLevel"=>11, "gender"=>0, "dead"=>false, "class"=>"witch-doctor", "last-updated"=>1352946041}, {"name"=>"Emma", "id"=>7153459, "level"=>60, "hardcore"=>false, "paragonLevel"=>0, "gender"=>1, "dead"=>false, "class"=>"monk", "last-updated"=>1347863170}, {"name"=>"Grumbar", "id"=>17793743, "level"=>60, "hardcore"=>false, "paragonLevel"=>0, "gender"=>0, "dead"=>false, "class"=>"barbarian", "last-updated"=>1352944313}, {"name"=>"BankerOne", "id"=>12215739, "level"=>1, "hardcore"=>false, "paragonLevel"=>0, "gender"=>1, "dead"=>false, "class"=>"monk", "last-updated"=>1351810350}] 

如果我向前迈出一步并使用my_profile.heroes [0]则返回

{"name"=>"Ziyi", "id"=>10692899, "level"=>60, "hardcore"=>false, "paragonLevel"=>87, "gender"=>1, "dead"=>false, "class"=>"wizard", "last-updated"=>1354337248} 

但是,我无法从上述结果中访问更多数据。

my_profile.heroes [0] .name返回NoMethodError,my_profile.heroes [0] [0]返回“nil”

我做错了吗?

提前致谢

赖安

1 个答案:

答案 0 :(得分:0)

这是一个哈希;使用哈希语法:

my_profile.heroes[0]['name']

除非东西用访问器方法包装哈希,否则它只是一个哈希。