You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查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 the if action == "1" block—this is totally unnecessary.
  • Error-prone nil check: When the word isn't in the hash, words[word] returns nil, and calling empty? on nil will throw a NoMethodError (since nil doesn't have an empty? 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 use words.has_key?(word) (it's an alias) or words[word].nil? (since accessing a non-existent key in a Ruby hash returns nil).
  • 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 case statement: Makes handling multiple actions cleaner than nested if statements.

内容的提问来源于stack exchange,提问作者Dion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:53:07