如果条件为真,则返回几行

时间:2016-02-20 01:25:30

标签: ruby

假设我有这个简单的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

如果案件12如何告诉程序再次请求输入,如果触发else,请继续使用此方法中的代码?我不想回到方法的开头,而只是想回到input变量声明。

2 个答案:

答案 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