Last active
December 16, 2017 19:00
-
-
Save Casual3498/fe05267cdfb860290bf7acdc8a28d579 to your computer and use it in GitHub Desktop.
4lesson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'csv' | |
require 'ostruct' | |
#require 'date' | |
filename = 'movies.txt' | |
keys_array = %i[href name year country date genres duration rank director actors] | |
films_array =[] | |
stat_keys_array = %i[month_number month_name films_count] | |
def output_films (arr) | |
arr.each do |film| | |
puts "#{film.name} :(#{film.date} ; #{film.genres}) - #{film.duration}" | |
puts "-----------" | |
end | |
end | |
#out stat hash by months | |
def output_stats (stat_hsh) | |
1.upto(12) do |month_number| | |
puts Date::MONTHNAMES[month_number] + ": #{stat_hsh[month_number]}" | |
end | |
#out 0 number month | |
puts "Month unknown: #{stat_hsh[0]}" if stat_hsh[0] | |
puts "\n\n" | |
end | |
#check if exists command line parameter | |
filename = ARGV[0] || filename | |
#check if exists file | |
unless File.exist?(filename) | |
puts "File #{filename} not found!" | |
return | |
end | |
#parse file and fill films_array | |
films_array = CSV.read(filename, col_sep: '|', headers: keys_array).map { |string| OpenStruct.new(string.to_h) } | |
puts "5 longest films:" | |
puts "----------------" | |
output_films films_array.sort_by { |film| film.duration[0..-3].to_f }.reverse.take(5) | |
puts "\n\n" | |
puts "10 comedys by date:" | |
puts "----------------_" | |
output_films films_array.select { |film| film.genres.include?('Comedy') }.sort_by(&:date).take(10) | |
puts "\n\n" | |
puts "All directors:" | |
puts "----------------" | |
puts films_array.map(&:director).uniq.sort_by { |director| director.split(' ').last } | |
puts "\n\n" | |
puts "non USA films count: " | |
puts films_array.count { |film| !film.country.include?('USA') } | |
puts "\n\n" | |
puts "Statistic on months (group_by)" | |
#fill stat hash | |
#stat_hash = films_array.group_by { |film| film.date[5..6].to_i }.each_with_object(Hash.new(0)) { |elem, hsh| hsh[elem[0]] = elem[1].count } | |
stat_hash = films_array.group_by { |film| film.date[5..6].to_i }.map { |month, months_films| [month, months_films.count] }.to_h | |
#out stat hash by months | |
output_stats stat_hash | |
puts "Statistic on months (each_with_object)" | |
#fill stat hash | |
stat_hash = films_array.each_with_object(Hash.new(0)) { |str, hsh| hsh[str[:date][5..6].to_i] += 1 } | |
#out stat hash by months | |
output_stats stat_hash |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment