如何检查Ruby哈希是否包含gets.chomp获取的单词及代码问题解决
How to Check if a Hash Contains a Word from User Input in Ruby
Let's break down the issues in your code and fix them step by step to properly check if the hash already has the word the user inputs:
First, let's list the problems in your original code:
- Redundant condition: You're checking
action == "1"again inside theif action == "1"block—this is totally unnecessary. - Error-prone nil check: When the word isn't in the hash,
words[word]returnsnil, and callingempty?onnilwill throw aNoMethodError(sincenildoesn't have anempty?method). - Broken string interpolation:
{Word}won't get replaced with the actual word—Ruby uses#{variable}for string interpolation. - No feedback for existing words: If the user inputs a word that's already been added, your code does nothing, which is confusing for the user.
- Unstoppable loop: There's no way to exit the program without force-quitting it.
Here's the fixed code:
words = {} while true puts "What do you want to do?" puts "1) Teach a word to Baby." puts "2) Check how many words Baby has learned." puts "3) Exit" action = gets.chomp case action when "1" puts "Write a word that you want to teach Baby:" word = gets.chomp.capitalize # Correct way to check if the hash DOESN'T have the word if !words.key?(word) words[word] = Time.now puts "Success! You taught #{word} to Baby." else puts "Baby already knows the word #{word}!" end when "2" puts "Baby has learned #{words.size} words so far." when "3" puts "Goodbye!" break else puts "Invalid option—please enter 1, 2, or 3." end end
Key fixes explained:
- Checking for existing keys:
words.key?(word)is the cleanest, most readable way to check if a hash contains a specific key. Alternatively, you could usewords.has_key?(word)(it's an alias) orwords[word].nil?(since accessing a non-existent key in a Ruby hash returnsnil). - Proper string interpolation:
#{word}replaces the placeholder with the actual user-input word. - Handled all cases: Added feedback for duplicate words, a way to exit the program, and error handling for invalid actions.
- Used a
casestatement: Makes handling multiple actions cleaner than nestedifstatements.
内容的提问来源于stack exchange,提问作者Dion
相关产品推荐
相关产品推荐

