如何从一个哈希的数组中提取哈希?

时间:2013-02-07 20:45:45

标签: ruby arrays hash enumerable

我正在编写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

2 个答案:

答案 0 :(得分:0)

疯狂猜测:

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

答案 1 :(得分:0)

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

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

注意:如果你有多个具有相同seasonnum的剧集,你应该使用group by并在这里有一组值。如果您只是通过方便的查找(一对一映射)构建剧集的哈希,那么index_by就是您想要的。

相关问题