0

我现在正在编写一个 API 解析器,并且正在努力格式化数据。

到目前为止,我有以下代码:

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

但是,唯一的问题是输出如下所示:

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?"
        }
    ]
}

所以二级散列的每个值都有一个冗余数组。我将如何删除这个数组并只拥有内部哈希?所以,例如我想要:

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"
        }
    ,

等等

编辑:这是完整的文件:

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

输入数据:http ://services.tvrage.com/feeds/episode_list.php?sid=5410

4

2 回答 2

0

胡乱猜测:

data.each { |season|
  episodes[season["no"].to_i] = season["episode"].group_by{ |i|
    i["seasonnum"].to_i
  }.first
}
于 2013-02-07T20:53:41.037 回答
0

当您真正想要 index_by (每个键一个条目)时,看起来您正在使用 group_by (具有相同键的条目数组)。

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

注意:如果您可以拥有多个具有相同季数的剧集,则应使用 group by 并在此处设置一组值。如果您只是通过方便的查找(一对一映射)构建剧集哈希,那么 index_by 就是您想要的。

于 2013-02-07T20:56:17.373 回答