如何检查哈希是否包含单词

时间:2018-04-07 13:31:43

标签: ruby

我想检查散列是否包含从gets.chomp检索到的单词。我试过这样:

words = {}
while true
  puts "What do you want to do?"
  puts "1) Learn a word to Baby."
  puts "2) Check how many words Baby has learn."
  action = gets.chomp
  if action == "1"
    puts "Write a word that you want to learn to Baby"
    word = gets.chomp.capitalize

这是问题所在:

if action == "1" && words[word].empty?
  words[word] = Time.now
  puts "With a succes you have learn {Word} to baby."
  if action == "1" && words[word].any?
    puts "This word is already learned by the baby."

我如何检查word(这可能有+1值,因为它已经存在)已经在哈希中,如果是,那么用户就无法向宝宝学习这个词。

1 个答案:

答案 0 :(得分:0)

您可以使用 words.include?(word)表示数组或 words.key?(word)表示哈希