Alex Marvick Alex Marvick - 4 months ago 19
Ruby Question

If/else statement via hash (Ruby)

I've created a hash (still relatively new with this concept) for a contact list where the keys are the names and the values are the phone numbers (both strings). The user is asked to take an action; here is one where you search a user's full name:

print "Search Name: "
name_search = gets.chomp

contact_book.each { |name, number| puts "The name entered corresponds to the following phone number: #{number}\n" if name.upcase == name_search.upcase }


I want to put an else statement that will notify the user if the input does not match up with any of the keys when looping through the hash, but was not able to figure out a way.

Answer

You can use Enumerable#select and manage the array returned

matched_names = contact_book.select { |name, number| name.upcase == name_search.upcase }
if matched_names.any?
   puts "The name entered corresponds to the following phone number: #{matched_names.first.last}\n"
else
   puts "The name entered has no matches\"
end 

Note that this highlights the fact that you could have more than one entry with the same name maybe.