当前位置: 动力学知识库 > 问答 > 编程问答 >

Can I access one of my case options from within my switch statement in Ruby?

问题描述:

I want to know if there is a way to access one of the case options from within another case option of the same switch statement:

For example:

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

网友答案:

Turn the case clause into a function:

def chooser(choice)
  case choice
  when '1'
    # your case clauses ...
  when '3'
    # ...
    if answer == 'yes'
      chooser(2)
    end
  end
end
网友答案:

You have many choices. Here's another:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: