Reputation: 142
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.
Upvotes: 1
Views: 1075
Reputation: 256
The other answers look like they will work, but seem quite verbose for what you are trying to accomplish. I guess it is only style preference, but for efficiency: If I want to see if a hash has a key I would do it like this in one line.
phone_num = contact_book[ name_key ]
puts ( phone_num ) ? "#{name_key}'s phone number is #{phone_num}" : "#{name_key} not found"
I notices someone trying to re-case everything everytime. For efficiency you would normally do this once on storing the name, not NxM times one searching for it.
Upvotes: 0
Reputation: 2586
Within a Hash you can lookup a key like this:
# convert all keys to upcase
contact_book_lookup = {}
hash.each_with_object(contact_book_lookup){ |(k, v), tmp_h| tmp_h[k.upcase] = v }
search_key = name_search.upcase
if contact_book_lookup.has_key? search_key
puts "The name entered corresponds to the following phone number: #{contact_book_lookup[search_key]}\n"
else
puts "The name entered has no matches\"
end
Upvotes: 1
Reputation: 30056
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.
Upvotes: 2