Dmytr1K
4/22/2016 - 4:20 PM

Lesson 4

Lesson 4

require 'csv'
require 'ostruct'

data_fields = [:url, :name, :year, :country, :date, :genre, :time, :rating, :director, :actors]

films = CSV.read("movies.txt", {col_sep: '|'} ).map {|e| OpenStruct.new(data_fields.zip(e).to_h)}

puts "\n5 longest movies:"
films.sort_by {|f| f.time.delete(" min").to_i} .reverse.first(5).each {|f| puts "#{f.name}: #{f.time}"}

puts "\nComedy, sorted by the release date:"
films.sort_by {|f| f.date} .select {|f| f.genre.include?("Comedy")} .each {|f| puts "#{f.name}: #{f.date}"}

puts "\nA list of all the directors in alphabetical order (no repeats!):"
films.map {|f| f.director} .sort.uniq.each {|f| puts f}

print "\nThe number of films made not in the USA: "
puts films.reject {|f| f.country.include?("USA")} .length

# Bonus!

puts "\nThe number of films grouped by director: "
films.group_by {|f| f.director} .sort_by {|v|} .each {|k, v| puts "#{k}: #{v.length} films"}
puts

puts "\nThe number of films in which starred each actor: "
films.map {|k| k.actors.chomp.split(",")} .flatten.sort.group_by {|i| i} .each {|k, v| puts "#{k}: #{v.length} films"}
puts

# Lesson 4

puts "\nThe number of films grouped by month: "
films.group_by {|f| f.date.length == 10 ? Date.strptime(f.date, '%Y-%m-%d').mon : f.date.length == 7 ? Date.strptime(f.date, '%Y-%m').mon : 0} .sort.each {|k, v| puts "#{k > 0 ? k : 'Unknown'}: #{v.length} films"}
puts