How do I finish the list filtering method?



  • Method M should be completed to filter the list of two key-digit films.

    puts films.m(genre: 'Comedy') 
    

    class Movie

    attr_reader :url, :title, :year, :country, :date, :genre, :length, :rating, :director, :actors

    def initialize(row)
    @url = row[0]
    @title = row[1]
    @year = row[2]
    @country = row[3]
    @date = row[4]
    @genre = row[5].to_s
    @length = row[6].to_i
    @rating = row[7]
    @director = row[8]
    @actors = row[9]
    end

    def has_genre?(field)
    @genre.include?(field)
    end

    def to_s
    "#{@title} (#{@year}), #{@genre} - #{@director}; #{@actors}"
    end
    end

    ____movielist.rb

    require 'csv'
    require 'date'
    require 'ostruct'

    require_relative 'movie.rb'
    KEYS = [:url, :title, :year, :country, :date, :genre, :length, :rating, :director, :actors]

    class MoviesCollection

    def initialize(filename)
    @filename = filename
    @movies = CSV.read(filename, col_sep: '|', write_headers: :true, headers: KEYS).
    map{|film| Movie.new(film)}
    end

    def all
    puts @movies.first(5) #all films
    end

    def sort_by (field) # sort by any field
    @movies.
    sort_by {|movie| movie.send(field)}
    end

    def m(filters)
    filters.each do |key, val|
    @movies.select {???

    def except_genre (genre) #delete genre
    @movies.
    select{|movie| !movie.has_genre?(genre)}.
    map{|movie| movie.title + " " + movie.genre.to_s}
    end

    def stats(field)
    if field == "date"
    @movies.map { |movie| (Date.parse(movie.date, '%Y-%m-%d').mon if movie.date.length == 10) }.compact.
    group_by{|i| i}.collect{|month, group| [month, group.count]}.to_h.sort.
    map{ |month, quant| Date::MONTHNAMES[month] + ' - ' + quant.to_s }
    else
    @movies.map{|movie| movie.send(field)}.
    sort_by{|field| field}.group_by{|field| field}.
    map{|field, group| [field, group.count]}
    end
    end
    end

    __mov.rb

    require_relative 'movielist.rb'
    require_relative 'movie.rb'

    filename = "movies.txt"
    films = MoviesCollection.new(filename)

    puts
    puts films.all # весь массив

    puts
    puts films.sort_by("title").first(5) # сортировка по заданному полю

    puts
    puts films.m(genre: 'Comedy') # фильмы определенного жанра + сортировка по стране

    puts
    puts films.except_genre("Sci-Fi").first(5) #фильмы за исключением определенного жанра, отсортированные по дате

    puts
    puts films.stats("date").first(5) # кол-во фильмов по запрашеваемому полю



  • May be as follows:

    def m(filters)
      res = []
      filters.each do |key, val|
        res += @movies.select { |x| x.send(key) == val }
      end
      res
    end
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2