2014-01-12 77 views
3

我想知道是否有訪問的情況下,選擇一個來自同一switch語句的另一種情況下,選擇內道:我可以在Ruby的switch語句中訪問我的一個case選項嗎?

例如:

puts "do you want [1], [2], [3], or [quit]?" 
choice = gets.chomp 

while choice != 'quit' 

    case choice 

    when '1' 
     puts "you chose one!" 

    when '2' 
     puts "you chose two!" 

    when '3' 
     puts "do you wish you had chosen two? [yes] [no] " 
     answer = gets.chomp 
     if answer == "yes" 
      # how do I access my case choice when '2' ??? 
     else 
      puts "you are happy with three!" 
     end 
    end 

end 

回答

1

打開的情況下子句到一個函數:

def chooser(choice) 
    case choice 
    when '1' 
    # your case clauses ... 
    when '3' 
    # ... 
    if answer == 'yes' 
     chooser(2) 
    end 
    end 
end 
+0

我剛剛添加的puts語句運行嗎?我不確定你是否還可以看到編輯,但是我所做的只是在'chooser(2)'下直接添加'puts「代碼就可以運行?」我只問,因爲它在大小寫區間內,我不太確定它們。 – stecd

+0

我測試了它,它沒有運行,有沒有辦法讓其他代碼在'chooser(「2」)下編寫來運行? – stecd

0

您有很多選擇。這是另一個:

answer = "no way, Jose" 

loop do 
    if answer == "yes" 
    answer = "nope" 
    choice = '2' 
    else  
    puts "do you want [1], [2], [3], or [quit]?" 
    choice = gets.chomp 
    end 

    case choice 
    when '1' 
    puts "you chose one!" 
    when '2' 
    puts "you chose two!" 
    when '3' 
    puts "do you wish you had chosen two? [yes] [no] " 
    answer = gets.chomp 
    puts "you are happy with three!" unless answer == "yes" 
    when 'quit' 
    break 
    end 
end 
相關問題