Ruby on rails 如何在Rails中访问子哈希变量

Ruby on rails 如何在Rails中访问子哈希变量,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正试图找出如何从Rails中的散列返回中获取第二级或子级。。。比如说 这就是我在Facebook上使用考拉宝石所得到的回报 {"id"=>"28898790358_10152709083080359", "from"=>{"category"=>"Tv channel", "category_list"=>[{"id"=>"169056916473899", "name"=>"Broadcasting & Media Production"}], "

我正试图找出如何从Rails中的散列返回中获取第二级或子级。。。比如说

这就是我在Facebook上使用考拉宝石所得到的回报

{"id"=>"28898790358_10152709083080359", "from"=>{"category"=>"Tv channel", "category_list"=>[{"id"=>"169056916473899", "name"=>"Broadcasting & Media Production"}], "name"=>"WGRZ - Channel 2, Buffalo", "id"=>"28898790358"}, "message"=>"Doctors remove 9-pound hairball from teen's stomach\nhttp://on.wgrz.com/1E12vpO", "picture"=>"https://fbexternal-a.akamaihd.net/safe_image.php?d=AQBYojdoFNbt05n5&w=158&h=158&url=http%3A%2F%2Fwww.gannett-cdn.com%2F-mm-%2Fe61500963820949c2654e6f754a9cd9d857b9f39%2Fc%3D0-238-3600-2268%26r%3Dx1803%26c%3D3200x1800%2Flocal%2F-%2Fmedia%2FUSATODAY%2FNone%2F2014%2F10%2F01%2F1412178695000-AFP-511998799.jpg", "link"=>"http://on.wgrz.com/1E12vpO", "name"=>"Doctors remove 9-pound hairball from teen's stomach", "caption"=>"www.usatoday.com", "description"=>"Kyrgyzstan girl, 18, was a habitual hair-chewer.", "icon"=>"https://fbstatic-a.akamaihd.net/rsrc.php/v2/y5/r/sXJx2UP7quc.png", "actions"=>[{"name"=>"Comment", "link"=>"https://www.facebook.com/28898790358/posts/10152709083080359"}, {"name"=>"Like", "link"=>"https://www.facebook.com/28898790358/posts/10152709083080359"}], "privacy"=>{"value"=>""}, "type"=>"link", "status_type"=>"shared_story", "created_time"=>"2014-10-01T19:19:08+0000", "updated_time"=>"2014-10-01T20:11:12+0000", "shares"=>{"count"=>75}, "likes"=>{"data"=>[{"id"=>"488026128001691", "name"=>"Liz Moeller"}, {"id"=>"10205169852351610", "name"=>"Anna Grazier"}, {"id"=>"591157491006916", "name"=>"Vanessa Huffer"}, {"id"=>"561759850622478", "name"=>"Ann Dante"}, {"id"=>"405685782913011", "name"=>"John Potempa"}, {"id"=>"10154648653570585", "name"=>"Joseph Braun"}, {"id"=>"825528997467246", "name"=>"Thomas Carney"}, {"id"=>"293748604151538", "name"=>"Tina Lazore"}, {"id"=>"10152796932723417", "name"=>"Patricia Fitzgerald Barnett"}, {"id"=>"840433475988223", "name"=>"Jessica Miller"}, {"id"=>"279812638893831", "name"=>"Alzina Roberta"}, {"id"=>"10152445879728226", "name"=>"Christina Joseph"}, {"id"=>"10152741973777766", "name"=>"Jenna Cipolla"}, {"id"=>"837871439580332", "name"=>"David Stubbe"}, {"id"=>"755004064560020", "name"=>"Dona M Blajszczak-Rosinski"}, {"id"=>"697656466970724", "name"=>"April Grigajtis"}, {"id"=>"992375559771", "name"=>"Joseph Rühlmann"}, {"id"=>"10204337209284065", "name"=>"Mike Mathieu"}, {"id"=>"848815905129472", "name"=>"Sue Graczyk Sobierajski"}, {"id"=>"930272426990088", "name"=>"Kenny L Motyka"}, {"id"=>"10203916182179015", "name"=>"Jessa Maeven Collins"}, {"id"=>"10152791313896477", "name"=>"Laura Cote"}, {"id"=>"10152683859774000", "name"=>"Sarah Beana"}, {"id"=>"10205227793438942", "name"=>"Sara Johnson-Molloy"}, {"id"=>"10204985250058770", "name"=>"Chrissy Meginley Stewart"}], "paging"=>{"cursors"=>{"after"=>"MTAyMDQ5ODUyNTAwNTg3NzA=", "before"=>"NDg4MDI2MTI4MDAxNjkx"}, "next"=>"https://graph.facebook.com/v2.1/28898790358_10152709083080359/likes?access_token=CAAKErEce2PkBAMZCH84asPkqOoptXt8KZBtFfkxOZAwZBTEG1sV8XLmaO75aahncO7HDJngtGFBGSEG1qYNLezwjHrJoKtTkLhFXuloGpbwAwtLnviZB2OZAz67QWDZC9oAw6UQ6MAFEAxNKoIyIZAKET0hKsjxKzE5QZAr1sO6GMiE4vBeYxVooqpuiHLZC1xsgPNyZBIdBATPvXF10aKEE7FC&limit=25&after=MTAyMDQ5ODUyNTAwNTg3NzA%3D"}}, "comments"=>{"data"=>[{"id"=>"10152709083080359_10152709086210359", "from"=>{"id"=>"1564134453806193", "name"=>"Linda Grillo"}, "message"=>"Omg", "can_remove"=>false, "created_time"=>"2014-10-01T19:21:20+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709088725359", "from"=>{"id"=>"10152378415284135", "name"=>"Stephanie Cooper"}, "message"=>"Sarah Cooper", "message_tags"=>[{"id"=>"10203592686995505", "name"=>"Sarah Cooper", "type"=>"user", "offset"=>0, "length"=>12}], "can_remove"=>false, "created_time"=>"2014-10-01T19:22:42+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709088950359", "from"=>{"id"=>"854070524605948", "name"=>"Alex Sharkey"}, "message"=>"That's a pretty strange addiction but glad she doesn't have 9lbs of hair in her stomach anymore.", "can_remove"=>false, "created_time"=>"2014-10-01T19:22:51+0000", "like_count"=>3, "user_likes"=>false}, {"id"=>"10152709083080359_10152709089390359", "from"=>{"id"=>"10100530741292425", "name"=>"Kailey Wood"}, "message"=>"John Wood", "message_tags"=>[{"id"=>"935102101201", "name"=>"John Wood", "type"=>"user", "offset"=>0, "length"=>9}], "can_remove"=>false, "created_time"=>"2014-10-01T19:22:59+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709090915359", "from"=>{"id"=>"580045458766925", "name"=>"Arlene Marie Garnham"}, "message"=>"Weird.", "can_remove"=>false, "created_time"=>"2014-10-01T19:24:02+0000", "like_count"=>1, "user_likes"=>false}, {"id"=>"10152709083080359_10152709091150359", "from"=>{"id"=>"644407049009877", "name"=>"Winnie Cooper"}, "message"=>"Wait.......what??", "can_remove"=>false, "created_time"=>"2014-10-01T19:24:13+0000", "like_count"=>2, "user_likes"=>false}, {"id"=>"10152709083080359_10152709092995359", "from"=>{"id"=>"10204886399418898", "name"=>"Debbie Lynn Rich"}, "message"=>"Shut the front door..that is hysterical!!", "can_remove"=>false, "created_time"=>"2014-10-01T19:25:38+0000", "like_count"=>2, "user_likes"=>false}, {"id"=>"10152709083080359_10152709093670359", "from"=>{"id"=>"10203002544480437", "name"=>"Michelle Mumothree"}, "message"=>"Um....meow", "can_remove"=>false, "created_time"=>"2014-10-01T19:25:59+0000", "like_count"=>7, "user_likes"=>false}, {"id"=>"10152709083080359_10152709095930359", "from"=>{"id"=>"851786061533069", "name"=>"Danny Barger"}, "message"=>"that's just nasty  an crazy ", "can_remove"=>false, "created_time"=>"2014-10-01T19:27:18+0000", "like_count"=>1, "user_likes"=>false}, {"id"=>"10152709083080359_10152709096430359", "from"=>{"id"=>"950617844952060", "name"=>"Nicole N Ryan Kroll"}, "message"=>"Nomnomnom add a little butter", "can_remove"=>false, "created_time"=>"2014-10-01T19:27:40+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709097245359", "from"=>{"id"=>"10204139630885286", "name"=>"Amy Choops Vealey"}, "message"=>"Effin disgusting", "can_remove"=>false, "created_time"=>"2014-10-01T19:28:07+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709097350359", "from"=>{"id"=>"880716621940584", "name"=>"Rob Kozak"}, "message"=>"ThTs why girls should shave down there!", "can_remove"=>false, "created_time"=>"2014-10-01T19:28:14+0000", "like_count"=>5, "user_likes"=>false}, {"id"=>"10152709083080359_10152709099970359", "from"=>{"id"=>"861465223872493", "name"=>"Bruce Rifenburg"}, "message"=>"Nervous girl huh!", "can_remove"=>false, "created_time"=>"2014-10-01T19:30:00+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709100600359", "from"=>{"id"=>"10203632325781260", "name"=>"Michelle Carlson Stephens"}, "message"=>"This is news ???", "can_remove"=>false, "created_time"=>"2014-10-01T19:30:34+0000", "like_count"=>1, "user_likes"=>false}, {"id"=>"10152709083080359_10152709100930359", "from"=>{"id"=>"798111513586382", "name"=>"Gayle Carey Balko"}, "message"=>"I new of a little girl who died of a bowel obstruction because she would bite her nails and had a habit of putting the end of her braids in her mouth. They found this large hair all and nails in her stomach. I will never forget it. That is why when I see little ones sucking on their hair I tell the parents that story!", "can_remove"=>false, "created_time"=>"2014-10-01T19:30:44+0000", "like_count"=>1, "user_likes"=>false}, {"id"=>"10152709083080359_10152709101730359", "from"=>{"id"=>"10204826234725533", "name"=>"Deborah Szlis"}, "message"=>"Gross", "can_remove"=>false, "created_time"=>"2014-10-01T19:31:13+0000", "like_count"=>1, "user_likes"=>false}, {"id"=>"10152709083080359_10152709104225359", "from"=>{"id"=>"992445030551", "name"=>"Kimberlee Ann"}, "message"=>"Maybe pica? It's a disorder where people eat things that aren't food. http://en.m.wikipedia.org/wiki/Pica_(disorder)", "can_remove"=>false, "created_time"=>"2014-10-01T19:33:12+0000", "like_count"=>3, "user_likes"=>false}, {"id"=>"10152709083080359_10152709104515359", "from"=>{"id"=>"10152706603435269", "name"=>"Kerry Murphy"}, "message"=>"Sounds like this child has some major mental issues", "can_remove"=>false, "created_time"=>"2014-10-01T19:33:23+0000", "like_count"=>1, "user_likes"=>false}, {"id"=>"10152709083080359_10152709105985359", "from"=>{"id"=>"809049082479473", "name"=>"Mary Beth Lazarski"}, "message"=>"Was it the kid that wanted his yearbook picture of him with his cat?", "can_remove"=>false, "created_time"=>"2014-10-01T19:34:28+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709106880359", "from"=>{"id"=>"775845355790712", "name"=>"Jim Sweetness McDonald Jr."}, "message"=>"Jenn Santiago", "message_tags"=>[{"id"=>"10152709167887440", "name"=>"Jenn Santiago", "type"=>"user", "offset"=>0, "length"=>13}], "can_remove"=>false, "created_time"=>"2014-10-01T19:35:02+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709107365359", "from"=>{"id"=>"798111513586382", "name"=>"Gayle Carey Balko"}, "message"=>"I worked in a kindergarten and you would be surprised how often kids do this!", "can_remove"=>false, "created_time"=>"2014-10-01T19:35:21+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709108230359", "from"=>{"id"=>"10152290902876268", "name"=>"Jessica Caplick"}, "message"=>"Weird...and rather gross. ", "can_remove"=>false, "created_time"=>"2014-10-01T19:35:56+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709111890359", "from"=>{"id"=>"773933259333099", "name"=>"Deepthi Koneru"}, "message"=>"Stop judging people..before u make nasty or sarcastic comment just get to know why she is doing it ..it's a disorder called trichtilomania.", "can_remove"=>false, "created_time"=>"2014-10-01T19:38:14+0000", "like_count"=>5, "user_likes"=>false}, {"id"=>"10152709083080359_10152709113670359", "from"=>{"id"=>"10203916182179015", "name"=>"Jessa Maeven Collins"}, "message"=>"Pica", "can_remove"=>false, "created_time"=>"2014-10-01T19:39:19+0000", "like_count"=>0, "user_likes"=>false}, {"id"=>"10152709083080359_10152709113680359", "from"=>{"id"=>"839132992775340", "name"=>"Tim Hunter"}, "message"=>"This girl has significant anxiety more than likely. It's not weird, it's not gross, it's a serious disorder. Grow up people", "can_remove"=>false, "created_time"=>"2014-10-01T19:39:20+0000", "like_count"=>8, "user_likes"=>false}], "paging"=>{"cursors"=>{"after"=>"MjU=", "before"=>"MQ=="}, "next"=>"https://graph.facebook.com/v2.1/28898790358_10152709083080359/comments?access_token=CAAKErEce2PkBAMZCH84asPkqOoptXt8KZBtFfkxOZAwZBTEG1sV8XLmaO75aahncO7HDJngtGFBGSEG1qYNLezwjHrJoKtTkLhFXuloGpbwAwtLnviZB2OZAz67QWDZC9oAw6UQ6MAFEAxNKoIyIZAKET0hKsjxKzE5QZAr1sO6GMiE4vBeYxVooqpuiHLZC1xsgPNyZBIdBATPvXF10aKEE7FC&limit=25&after=MjU%3D"}}}
我可以用
东西[“来自”][“类别”]
抓住它。。。但是,尝试获取例如
某物[“共享”][“计数”]
。。。。。。。对于nil:NilClass,我得到一个错误
未定义的方法
[]`

something[“shares”]
确实会返回值
--count:73
,我已经读到
count
可能是或其他

如何检索
shares->count
number有什么建议吗

模型中的示例代码或逻辑,用于在facebook中为每个返回的
home
帖子创建DB条目

def self.pull

    pull = user.facebook.get_connection("me", "home")

    // above returns a long hash and for many stories on the homepage of facebook
    // so for each story we pull i want to grab few items from the hash
    // for example the share count

    pull.each do |story|
        user.model.create({story_id: story[:id], shares_count: story["shares"]["count"], author: story["from"]["name"]})
    end

    // the above works for the story[:id] and for story["from"]["name"] but not on story["shares"]["count"]
end

可能您正在尝试对nil对象执行哈希操作。在从对象获取数据之前,您应该检查nil条件

 If something or something["shares"] is nil
 Then something["shares"]["count"]
 returns ==> NoMethodError: undefined method `[]' for nil:NilClass

检查nil条件并继续,这可能会对您有所帮助。

可能是您正在尝试对nil对象执行哈希操作。您应该在从对象获取数据之前检查nil条件

 If something or something["shares"] is nil
 Then something["shares"]["count"]
 returns ==> NoMethodError: undefined method `[]' for nil:NilClass

检查nil条件并继续,这可能会对您有所帮助。

可能是您正在尝试对nil对象执行哈希操作。您应该在从对象获取数据之前检查nil条件

 If something or something["shares"] is nil
 Then something["shares"]["count"]
 returns ==> NoMethodError: undefined method `[]' for nil:NilClass

检查nil条件并继续,这可能会对您有所帮助。

可能是您正在尝试对nil对象执行哈希操作。您应该在从对象获取数据之前检查nil条件

 If something or something["shares"] is nil
 Then something["shares"]["count"]
 returns ==> NoMethodError: undefined method `[]' for nil:NilClass

检查nil condition&继续这可能会对您有所帮助。

如注释中所述,这不是散列,而是散列的序列化,因此您首先需要将其解析回Ruby对象:

require 'json'

json = '{"data":[{"id":1,"from":{"category":"Musician/band"}}]}'
hash = JSON[json]
Ruby的JSON类是标准库的一部分,非常易于使用。基本上,您可以传递一个字符串,它将尝试将其解析回一个对象,或者传递一个对象,它将返回序列化为字符串的对象。这是最灵活的解析和序列化方法

此时,
散列
是一个散列:

hash.class # => Hash
而且,您可以深入研究它,以访问它包含的任何内容:

hash['data'].first['id'] # => 1
为了方便起见,不要编写越来越长的键和索引链,而是将元素分配给变量:

from = hash['data'].first['from'] # => {"category"=>"Musician/band"}
from
成为散列和数组中的占位符,使其易于处理特定元素:

from['category'] # => "Musician/band"
您应该养成使用IRB或Pry戳东西的习惯,并使用减少的数据样本来防止数据变得笨拙,至少在您习惯使用JSON和哈希之前是这样。例如,Pry中的会话如下所示:

[1] (pry) main: 0> require 'json'
true
[2] (pry) main: 0> json = '{"data":[{"id":1,"from":{"category":"Musician/band"}}]}'
"{\"data\":[{\"id\":1,\"from\":{\"category\":\"Musician/band\"}}]}"
[3] (pry) main: 0> hash = JSON[json]
{
    "data" => [
        [0] {
              "id" => 1,
            "from" => {
                "category" => "Musician/band"
            }
        }
    ]
}
[4] (pry) main: 0> hash.class
Hash < Object
[5] (pry) main: 0> hash['data'].first['id']
1
[6] (pry) main: 0> from = hash['data'].first['from']
{
    "category" => "Musician/band"
}
[7] (pry) main: 0> from['category']
"Musician/band"
[1](pry)main:0>需要“json”
真的
[2] (pry)main:0>json='{“数据”:[{“id”:1,“发件人”:{“类别”:“音乐家/乐队”}]}'
“{\'data\':[{\'id\':1,\'from\':{\'category\':\'音乐家/乐队\'}]}”
[3] (pry)main:0>hash=JSON[JSON]
{
“数据”=>[
[0] {
“id”=>1,
“从”=>{
“类别”=>“音乐家/乐队”
}
}
]
}
[4] (pry)main:0>hash.class
哈希<对象
[5] (pry)main:0>散列['data']。第一个['id']
1.
[6] (pry)main:0>from=hash['data']。第一个['from']
{
“类别”=>“音乐家/乐队”
}
[7] (撬动)干管:0>来自['category']
“音乐家/乐队”

您可以轻松地研究如何访问结构,而无需编辑文件并运行它。

如注释中所述,这不是散列,而是散列的序列化,因此您首先需要将其解析回Ruby对象:

require 'json'

json = '{"data":[{"id":1,"from":{"category":"Musician/band"}}]}'
hash = JSON[json]
Ruby的JSON类是标准库的一部分,非常易于使用。基本上,您可以传递一个字符串,它将尝试将其解析回一个对象,或者传递一个对象,它将返回序列化为字符串的对象。这是最灵活的解析和序列化方法

此时,
散列
是一个散列:

hash.class # => Hash
而且,您可以深入研究它,以访问它包含的任何内容:

hash['data'].first['id'] # => 1
为了方便起见,不要编写越来越长的键和索引链,而是将元素分配给变量:

from = hash['data'].first['from'] # => {"category"=>"Musician/band"}
from
成为散列和数组中的占位符,使其易于处理特定元素:

from['category'] # => "Musician/band"
您应该养成使用IRB或Pry戳东西的习惯,并使用减少的数据样本来防止数据变得笨拙,至少在您习惯使用JSON和哈希之前是这样。例如,Pry中的会话如下所示:

[1] (pry) main: 0> require 'json'
true
[2] (pry) main: 0> json = '{"data":[{"id":1,"from":{"category":"Musician/band"}}]}'
"{\"data\":[{\"id\":1,\"from\":{\"category\":\"Musician/band\"}}]}"
[3] (pry) main: 0> hash = JSON[json]
{
    "data" => [
        [0] {
              "id" => 1,
            "from" => {
                "category" => "Musician/band"
            }
        }
    ]
}
[4] (pry) main: 0> hash.class
Hash < Object
[5] (pry) main: 0> hash['data'].first['id']
1
[6] (pry) main: 0> from = hash['data'].first['from']
{
    "category" => "Musician/band"
}
[7] (pry) main: 0> from['category']
"Musician/band"
[1](pry)main:0>需要“json”
真的
[2] (pry)main:0>json='{“数据”:[{“id”:1,“发件人”:{“类别”:“音乐家/乐队”}]}'
“{\'data\':[{\'id\':1,\'from\':{\'category\':\'音乐家/乐队\'}]}”
[3] (pry)main:0>hash=JSON[JSON]
{
“数据”=>[
[0] {
“id”=>1,
“从”=>{
“类别”=>“音乐家/乐队”
}
}
]
}
[4] (pry)main:0>hash.class
哈希<对象
[5] (pry)main:0>散列['data']。第一个['id']
1.
[6] (pry)main:0>from=hash['data']。第一个['from']
{
“类别”=>“音乐家/乐队”
}
[7] (撬动)干管:0>来自['category']
“音乐家/乐队”

您可以轻松地研究如何访问结构,而无需编辑文件并运行它。

如注释中所述,这不是散列,而是散列的序列化,因此您首先需要将其解析回Ruby对象:

require 'json'

json = '{"data":[{"id":1,"from":{"category":"Musician/band"}}]}'
hash = JSON[json]
Ruby的JSON类是标准库的一部分,非常易于使用。基本上,您可以传递一个字符串,它将尝试将其解析回一个对象,或者传递一个对象,它将返回序列化为字符串的对象。这是最灵活的解析和序列化方法

此时,
散列
是一个散列:

hash.class # => Hash
而且,您可以深入研究它,以访问它包含的任何内容:

hash['data'].first['id'] # => 1
为了方便起见,不要编写越来越长的键和索引链,而是将元素分配给变量:

from = hash['data'].first['from'] # => {"category"=>"Musician/band"}
from
成为散列和数组中的占位符,使其易于处理特定元素:

from['category'] # => "Musician/band"
你应该进入哈比河