gpt4 book ai didi

ruby - 试图在 case 语句中引用更早的 'case'

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:18 29 4
gpt4 key购买 nike

当有人试图更新当前未存储在我的散列中的值时,我想立即返回 when 'add' 而无需重新启动整个 case声明,因为我已经知道他们想要添加并且不想再次提示他们。

有没有一种方法可以在不重新启动整个案例的情况下返回我的代码的case choice -> when“add”部分声明?

我知道我可以使用嵌套的 case 语句,但如果没有必要,我宁愿不复制/粘贴相同的代码。

hash = {}
puts "Would you like to add or update this hash?"
choice = gets.chomp
case choice
when "add"
puts "What key you like to add?"
key = gets.chomp
puts "With what value?"
value = gets.chomp
hash[key] = value
when "update"
puts "Which key would you like to update?"
key = gets.chomp
if hash[key].nil?
puts "Key not present, would you like to add it?"
#here I would like the code that references back to "when 'add'" if the user types 'yes'

抱歉代码突然结束。我不想在解决方案中加入任何不必要的东西。

最佳答案

创建一个将功能包装在该案例中的方法/函数。然后你可以从两个地方调用那个函数

hash = {}
def add_key
puts "What key you like to add?"
key = gets.chomp
puts "With what value?"
value = gets.chomp
hash[key] = value
end
puts "Would you like to add or update this hash?"
choice = gets.chomp
case choice
when "add"
add_key
when "update"
puts "Which key would you like to update?"
key = gets.chomp
if hash[key].nil?
puts "Key not present, would you like to add it?"
add_key

关于ruby - 试图在 case 语句中引用更早的 'case',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31817031/

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