Ruby 从散列随机化键值对
我正在构建一个简单的词汇测验,为用户提供一个预先确定的哈希值,并将用户的响应作为输入。如果用户的输入与值的对应键匹配,则程序将移动到下一个值,并重复此过程,直到哈希中的所有键-值对都已计算完毕 在其当前状态下,测验将按照从头到尾的顺序,逐个提示用户散列中的值 但是,为了使测验更加困难,我希望测验提供散列中的随机值,而不是以特定顺序 简单英语…我如何让vocab测验从其库中随机给出定义,而不是每次都以相同的顺序打印相同的定义 我的代码如下。非常感谢大家的帮助Ruby 从散列随机化键值对,ruby,hash,hashmap,each,key-value,Ruby,Hash,Hashmap,Each,Key Value,我正在构建一个简单的词汇测验,为用户提供一个预先确定的哈希值,并将用户的响应作为输入。如果用户的输入与值的对应键匹配,则程序将移动到下一个值,并重复此过程,直到哈希中的所有键-值对都已计算完毕 在其当前状态下,测验将按照从头到尾的顺序,逐个提示用户散列中的值 但是,为了使测验更加困难,我希望测验提供散列中的随机值,而不是以特定顺序 简单英语…我如何让vocab测验从其库中随机给出定义,而不是每次都以相同的顺序打印相同的定义 我的代码如下。非常感谢大家的帮助 vocab_words = { "
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
使用:
random\u keys=vocab\u 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
非常感谢!使用了你的建议,效果很好。谢谢你的帮助。