假设我有这个简单的if-elsif-else
代码块。
def
# some code...
input = get.chomp
if input == 1
puts "foo"
elsif input == 2
puts "bar"
else
# exit
end
# some more code...
end
如果案件1
和2
如何告诉程序再次请求输入,如果触发else
,请继续使用此方法中的代码?我不想回到方法的开头,而只是想回到input
变量声明。
答案 0 :(得分:1)
def
# some code...
loop do
input = get.chomp
if input == 1
puts "foo"
break
elsif input == 2
puts "bar"
break
end
end
# some more code...
end
注意:您的两个if
/ elsif
条件永远不会得到满足。
答案 1 :(得分:0)
# main procedure
# defined here so other functions could be declared after
# the main procedure is called at the bottom
def main
loop do
puts "Insert a number"
input = gets.chomp.to_i
if isValidInput input
puts case input
when 1
"foo"
when 2
"bar"
end
break
end
end #loop
puts "Other code would execute here"
end
# Validity Checker
# makes sure your input meets your condition
def isValidInput(input)
if [1,2].include? input
return true
end
return false
end
main