mardi 4 août 2015

Trying to reference earlier 'case' in a case statement

When someone tries to update a value that is not currently stored in my hash, I would like to immediately reference back to "when 'add'" without restarting the entire case statement (since I already know they want to add and don't want to prompt them again). Is there a way to reference back to the case choice -> when "add" section of my code without restarting the entire case statement? I know I could use nested case statements but I would rather not copy/paste identical code if I don't have to.

Also, sorry for the abrupt ending of the code. I just didn't want to put in anything unnecessary to the solution.

    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'    



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire