I want to make a filter class in which I have three methods: name, genre, and year. I want to filter a list of movies, in which every object has a name, title and a year, on multiple criteria.
I can’t figure out how to do this. For example:
Filter.name("Batman") & Filter.genre("Drama") | !Filter.year(2001)
I tried to keep the filter fields in a list [name => batman, genre=>drama], and so on, but the operators (especially or (|)) are bugging me.
I’m accepting any ideas.
The functionality you want fits naturally into Enumerable’s select, which Array inherits.
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.
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.
Here’s how I’d write that functionality, but doing it in a way I consider more Ruby-like:
I used a hash for the Movie class, because it’s quicker. It’s also a dirtier way to go, but it works.
Here’s the output of running the code:
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.