在哈希中散列哈希中的数组中的哈希值?

时间:2014-03-07 05:08:48

标签: ruby hash

我有一个对象eplist,看起来像这样......

{'show' => {'name' => 'stella', 'total_seasons' => '1','episodelist' => {'season' => {'episode' => [{'epnum' => '1', 'seasonnum' => '01', 'prodnum' => '101', 'airdate' => '2005-06-28', 'title' => 'pilot'},{'epnum' => '2', 'seasonnum' => '02', 'prodnum' => '103', 'airdate' => '2005-07-05', 'title' => 'campaign'}]}}}}

代表电视指南。我的愿望是遍历它,并为每一集吐出像第1季,第7集:TITLE 这样的字符串。

我的麻烦来自迭代它。我似乎无法编写一组正常工作的循环!我试过了

eplist['show']['episodelist'].each do |season|
    season.each do |episode|
        puts episode['title']
    end
end

但这只是输出空行 - 没有错误或任何东西。尝试做第三个.each循环,它放出它看到的任何元素,给我undefined method每个'为“季节”:String`错误。

在这种情况下,我应该如何迭代这个对象?

2 个答案:

答案 0 :(得分:4)

从您的数据结构中,尝试:

因为这是哈希,

eplist['show']['episodelist']['season']['episode'].each do |data|
  puts data['title']
  # you can use the below code to get the preferred format
  # puts "Season #{data['seasonnum']}, Episode #{data['epnum']}: #{data['title']}"
end

答案 1 :(得分:0)

如果你想保留你的语法,那就是

eplist['show']['episodelist'].each do |season,episodes|
  episodes['episode'].each do | episode|
    puts episode['title']
  end
end

看起来像一个奇怪的哈希结构虽然可能更有意义

{'show' => 
  {'name' => 'stella', 'total_seasons' => '1','seasons' => [
    {'season_number' => 1,'episodes' => [
       {'epnum' => '1', 'seasonnum' => '01', 'prodnum' => '101', 'airdate' => '2005-06-28', 'title' => 'pilot'},
       {'epnum' => '2', 'seasonnum' => '02', 'prodnum' => '103', 'airdate' => '2005-07-05', 'title' => 'campaign'}]
    }]
  }
}

然后这会更好看

 eplist.each do |show,details|
    details['seasons'].each do |season|
       season['episodes'].each do |episode|
         puts episode['title']
       end 
    end
 end