试图参考前面的案例'案例陈述中

时间:2015-08-04 18:52:45

标签: ruby loops case

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

有没有办法引用回case choice - >我的代码的when "add"部分没有重新启动整个case语句?

我知道我可以使用嵌套的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'    

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

1 个答案:

答案 0 :(得分:3)

创建一个包含该案例内部功能的方法/函数。然后你可以从两个地方调用该函数

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