0

I have a hash filled with 32 strings of the names and locations of NFL teams (e.g. "Baltimore Ravens", "Pittsburgh Steelers," etc.)

I'm writing a class called def search which asks the user to enter the name of a team and then runs a while loop that looks through the hash, tries to match the user inputted string with a piece of a string in the hash and return the full value.

For example, if you enter Ravens, it should return "Baltimore Ravens"

I'm not sure of the correct things to enter in my code to take the piece of the string entered and try to match it with the full string and return a result. Googling hasn't helped answer my question so I'm turning to you great people.

Thanks in advance for your help.


Real code:

def search(team, nfl)
  favTeam = nfl.find_all { |i| i = team }
  puts favTeam
end

That's printing all of the teams in the nfl Array (not a Hash, I made a mistake). Not entirely sure what I'm supposed to write to make it look for team (which is what the user has already inputted) to compare it to the values in the array.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151

1 Answers1

3

Given your hash in h and the substring you're looking for in s:

key = h.detect { |k, v| v.downcase.index(s.downcase) }.to_a.first

will give you the first key in h whose value contains s (case insensitive). The to_a call is just a simple way to convert a possible nil return to an empty array without requiring an extra check.

If you wanted them all, then:

keys = h.find_all { |k, v| v.downcase.index(s.downcase) }.map(&:first)

You might want to downcase s before the iteration but it won't matter much for only 32 values.

References:


Updates to match the updated question: Since you actually have an array instead of a hash:

matches = nfl.find_all { |name| name.downcase.index(team.downcase) }

You'd still use find_all (or select if you like that name better), just adjust the block argument to match what find_all on an Array gives you.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • So this is my code: def search (team, nfl) favTeam = nfl.find_all { |i| i = team } puts favTeam end That's printing all of the teams in the nfl array (not a hash, I made a mistake). Not entirely sure what I'm supposed to write to make it look for team (which is what the user has already inputted) to compare it to the values in the array. – Zack Shapiro Sep 05 '11 at 03:42