gpt4 book ai didi

ruby - 从哈希中随机化键值对

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:10 25 4
gpt4 key购买 nike

我正在构建一个简单的词汇测验,为用户提供一个来自预先确定的哈希的值,并将他或她的回答作为输入。如果用户的输入与值的对应键匹配,程序将继续下一个值,并重复此过程,直到哈希中的所有键值对都已被计算在内。

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

但是,为了使测验更难,我希望测验提供哈希中的随机值,没有特定顺序。

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

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

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_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

关于ruby - 从哈希中随机化键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40401937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com