从散列中随机化键值对

时间:2016-11-03 12:48:39

标签: ruby hash hashmap each key-value

我正在构建一个简单的词汇测验,为用户提供预定哈希值,并将他或她的回答作为输入。如果用户的输入与值的相应键匹配,程序将继续执行下一个值,并重复此过程,直到考虑了散列中的所有键值对。

在当前状态下,测验从头到尾按顺序逐个提示用户输入哈希值。

但是,为了使测验更加困难,我希望测验能够从哈希中提供RANDOM值,而不是特定的顺序。

普通英语...如何让词汇测验从其库中吐出随机定义,而不是每次都以相同的顺序打印相同的定义?

我的代码如下。非常感谢大家的帮助!

vocab_words = {
  "class" => "Tell Ruby to make a new type of thing",
  "object" => "Two meanings: The most basic type of thing, and any instance of some thing",
  "instance" => "What you get when you tell Ruby to create a class",
  "def" => "How you define a function inside a class"
}

vocab_words.each do |word, definition|
  print vocab_words[word] + ": "
  answer = gets.to_s.chomp.downcase

    while answer != "%s" %word
      if answer == "help"
        print "The answer is \"%s.\" Type it here: " %word
        answer = gets.to_s.chomp.downcase
      else
        print "Nope. Try again: "
        answer = gets.to_s.chomp.downcase
      end
    end
  end

1 个答案:

答案 0 :(得分:1)

使用:random_keys = vocab_words.keys.shuffle,如此:

vocab_words = {
  "class" => "Tell Ruby to make a new type of thing",
  "object" => "Two meanings: The most basic type of thing, and any instance of some thing",
  "instance" => "What you get when you tell Ruby to create a class",
  "def" => "How you define a function inside a class"
}

random_keys = vocab_words.keys.shuffle
random_keys.each do |word|
  print vocab_words[word] + ": "
  answer = gets.to_s.chomp.downcase

  if answer == "help"
    print "The answer is \"%s.\" Type it here: " %word
    answer = gets.to_s.chomp.downcase
  else
    while answer != "%s" %word
      print "Nope. Try again: "
      answer = gets.to_s.chomp.downcase
    end
  end
end