I have an object, eplist
, that looks like this...
{'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'}]}}}}
representing a TV guide. My desire is to iterate through it, and spit out a string like Season 1, Episode 7: TITLE for each episode.
My trouble comes from iterating through it. I just can't seem to write a set of loops that works properly! I've tried
eplist['show']['episodelist'].each do |season|
season.each do |episode|
puts episode['title']
end
end
But that just outputs blank rows -- no error or anything. Trying to do a third .each loop where it puts out whatever element it sees gives me the undefined method
each' for "Season":String` error.
In this case, how should I iterate over this object?
From your data structure, try:
As this is a hash,
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
If you would like to keep your syntax it would be
eplist['show']['episodelist'].each do |season,episodes|
episodes['episode'].each do | episode|
puts episode['title']
end
end
Seems like a strange hash structure though might make more sense as
{'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'}]
}]
}
}
Then this would read nicer
eplist.each do |show,details|
details['seasons'].each do |season|
season['episodes'].each do |episode|
puts episode['title']
end
end
end
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.