Search code examples
rubyclassweb-scrapingclass-method

Ruby: Searching an array based off of multiple keywords


Best way to search for multiple keywords through an array of instances (not like that matters, but that is my certain scenario)

all = [@sport = "string", @description = "string", @time = "string", 
@matchup = "string"]

The strings within these instances are scraped info from a TV schedule. Currently, I am using "include?" and my app is working fine, but I feel like it can be refactored to be cleaner and more efficient.

Here is my current setup:

def self.select_by(sport)
    all.select {|object| object.sport.include?(sport) || 
    object.description.include?(sport) || object.matchup.include?(sport) || 
    object.time.include?(sport) }
end

I have 10 class methods to plug into the select_by method. Example of one is below.

def self.football
    select_by("Football")
end

You get the picture :D

I set each self.insert_sport to a variable in my CLI and plug that variable into another method to display the proper breakdown based off of the instances in the array (sport, description, matchup, time).

I was just wondering is there a way to add more keywords without breaking my functionality too much. As it stands, it works fairly nicely because the schedule is predictable and the keywords are consistent but since I am new to programming, I want to make sure to get in the habit of covering all my bases.


Solution

  • I would refactor the select_by method a bit:

    ATTRIBUTES = %i[sport description matchup time]
    
    def self.select_by(sport)
      all.select do |object|
        ATTRIBUTES.any? { |attr| object.public_send(attr).include?(sport) }
      end
    end 
    

    Adding more attributes would be as simple as adding the attributes name to the constant.