简体   繁体   中英

How do I extract the hash from an array of one hash?

I'm writing an API parser at the moment, and I'm working on formatting the data nicely.

So far, I have the following code:

data.each {|season| episodes[season["no"].to_i] = season["episode"].group_by{|i| i["seasonnum"].to_i}}

However, the only issue with this is that the output comes out like this:

8 => {
     1 => [
        [0] {
                "epnum" => "150",
            "seasonnum" => "01",
              "prodnum" => "3X7802",
              "airdate" => "2012-10-03",
                 "link" => "http://www.tvrage.com/Supernatural/episodes/1065195189",
                "title" => "We Need to Talk About Kevin"
        }
    ],
     2 => [
        [0] {
                "epnum" => "151",
            "seasonnum" => "02",
              "prodnum" => "3X7803",
              "airdate" => "2012-10-10",
                 "link" => "http://www.tvrage.com/Supernatural/episodes/1065217045",
                "title" => "What's Up, Tiger Mommy?"
        }
    ]
}

So there's a redundant array in each value of the secondary hash. How would I remove this array and just have the inside hash? So, for example I want:

8 => {
     1 => {
                "epnum" => "150",
            "seasonnum" => "01",
              "prodnum" => "3X7802",
              "airdate" => "2012-10-03",
                 "link" => "http://www.tvrage.com/Supernatural/episodes/1065195189",
                "title" => "We Need to Talk About Kevin"
        }
    ,

etc.

EDIT: Here's the full file:

require 'httparty'
require 'awesome_print'
require 'debugger'
require 'active_support'

episodes = Hash.new{ [] }
response = HTTParty.get('http://services.tvrage.com/feeds/episode_list.php?sid=5410')
data = response.parsed_response['Show']['Episodelist']["Season"]

data.each { |season|
  episodes[season["no"].to_i] = season["episode"].group_by{ |i|
    i["seasonnum"].to_i
  }
}

ap episodes

Input data: http://services.tvrage.com/feeds/episode_list.php?sid=5410

Wild guess:

data.each { |season|
  episodes[season["no"].to_i] = season["episode"].group_by{ |i|
    i["seasonnum"].to_i
  }.first
}

It looks like you're using group_by (array of entries with same key) when you really want index_by (one entry per key).

data.each {|season| episodes[season["no"].to_i] = season["episode"].index_by {|i| i["seasonnum"].to_i}}

NOTE: If you can have MORE than one episode with the same seasonnum, you SHOULD use group by and have an array of values here. If you're just building a hash of episodes with a convenient lookup (one to one mapping), then index_by is what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM