Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The functionality you want fits naturally into Enumerable's select, which Array inherits. </p> <p>Because you're talking about a list, AKA, array, it's a natural fit to use select to determine whether your movies meet your criteria by building upon that, instead of passing them into a method. </p> <p>A separate Filter class will not fit the Ruby-way as well. Consider sub-classing Array for your movie list, and adding a filter method that takes your criteria as parameters.</p> <p>Here's how I'd write that functionality, but doing it in a way I consider more Ruby-like:</p> <pre><code>require 'pp' class Movies &lt; Array def initialize(*movies) super(movies) end def filter(criteria={}) self.select{ |m| criteria.all?{ |c, v| m.send(c, v) } } end end class Movie def initialize(attributes={}) @movie = attributes end def name(t) case t when Regexp @movie[:name][t] when String @movie[:name] == t end end def genre(g) @movie[:genre] == g end def year(y) @movie[:year] == y end end movies = Movies.new( Movie.new(name: 'Batman', genre: 'Drama', year: 2001), Movie.new(name: 'The Shawshank Redemption', genre: 'Drama', year: 1994), Movie.new(name: 'Raiders of the Lost Ark', genre: 'Action', year: 1981) ) pp movies.filter(year: 1981) pp movies.filter(genre: 'Drama', year: 2001) pp movies.filter(name: /redemption/i) </code></pre> <p>I used a hash for the Movie class, because it's quicker. It's also a dirtier way to go, but it works.</p> <p>Here's the output of running the code:</p> <pre><code>[#&lt;Movie:0x007ff7b191ffb8 @movie={:name=&gt;"Raiders of the Lost Ark", :genre=&gt;"Action", :year=&gt;1981}&gt;] [#&lt;Movie:0x007ff7b1920260 @movie={:name=&gt;"Batman", :genre=&gt;"Drama", :year=&gt;2001}&gt;] [#&lt;Movie:0x007ff7b19200d0 @movie={:name=&gt;"The Shawshank Redemption", :genre=&gt;"Drama", :year=&gt;1994}&gt;] </code></pre> <p>The actual flow of filtering the movies fits into how we normally write Ruby code. It could be done even better, but that's a start.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. COThat was very helpful.
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload