在if / else语句中创建循环

时间:2014-02-21 17:34:14

标签: ruby conditional-statements

我正处于学习Ruby的早期阶段,并在尝试为我的某个程序创建条件语句时遇到了问题。如果orignal不符合前两个条件的标准,我基本上希望它循环并获取新的输入值。

例如:

puts "Choose either the 'red' or 'blue' pill"

choice = gets.to_s.downcase.chomp

if choice == red
    puts "Fasten your seatbelt dorothy 'cause kansas is going bye-bye" 
elsif choice == "blue"
   puts "The story ends, you wake up in your bed and believe whatever you want to believe"
else
    puts "You have to choose one"
end

4 个答案:

答案 0 :(得分:3)

这是另一个常见的构造:

loop do
  puts "Choose either an 'upper' or a 'downer'"

  case gets.downcase.chomp
  when "upper"
    puts "Fasten your seatbelt dorothy 'cause kansas is going bye-bye"
    break 
  when "downer"
    puts "The story ends, you wake up and believe whatever you want to believe"
    break
  else
    puts "You have to choose one"
  end
end

答案 1 :(得分:1)

begin
  puts "Choose either the 'red' or 'blue' pill"
  choice = gets.to_s.downcase.chomp

  if choice == "red"
    puts "Fasten your seatbelt dorothy 'cause kansas is going bye-bye" 
  elsif choice == "blue"
    puts "The story ends, you wake up in your bed and believe whatever you want to believe"
  else
    puts "You have to choose one"
    choice = "invalid"
  end
end while(choice == "invalid")

控制台输出:

Choose either the 'red' or 'blue' pill
#empty input
You have to choose one
Choose either the 'red' or 'blue' pill
red
Fasten your seatbelt dorothy 'cause kansas is going bye-bye
 => nil 

答案 2 :(得分:1)

对于这种情况,Ruby的throwcatch如何:

def ask
  puts "Choose either the 'red' or 'blue' pill"
  choice = gets.downcase.chomp
  if choice == 'red'
    puts "Fasten your seatbelt dorothy 'cause kansas is going bye-bye" 
  elsif choice == "blue"
    puts "The story ends, you wake up in your bed and believe whatever you want to believe"
  else
    puts "You have to choose one"
    throw :done,ask
  end
end

catch(:done) do
  ask
end

让我们运行代码:

(arup~>Ruby)$ ruby -v a.rb
ruby 2.0.0p0 (2013-02-24 revision 39474) [i686-linux]
Choose either the 'red' or 'blue' pill
foo
You have to choose one
Choose either the 'red' or 'blue' pill
bar
You have to choose one
Choose either the 'red' or 'blue' pill
blue
The story ends, you wake up in your bed and believe whatever you want to believe
(arup~>Ruby)$ 

答案 3 :(得分:0)

class WrongChoice < StandardError
end

puts "Choose either the 'red' or 'blue' pill"

begin
  choice = gets.to_s.downcase.chomp
  raise WrongChoice.new unless ['blue', 'red'].include? choice 
  if choice == red
    puts "Fasten your seatbelt dorothy 'cause kansas is going bye-bye" 
  else 
   puts "The story ends, you wake up in your bed and believe whatever you want to"
  end
rescue WrongChoice
  puts "You have to choose one"
  retry
end