Ruby重新运行我的脚本

时间:2015-01-28 17:29:08

标签: ruby loops

如果用户要求,我希望我的ruby代码重新运行我的代码。为此,我最后提出了一个问题,询问用户是否要继续使用它。我想要它,以便如果gets.chomp()= yes它重新运行程序。

我想把它变成一个循环,但我不确定如何采用这种方法。

require './codes/AlName.rb'
require './codes/UserName.rb'

system 'cls'



    puts("What do you want me to do?")
    command = gets.chomp()

    commands = [
        "time",
        "done",
        "chat",
        "help",
    ]

    #display time (Time.now)
    if command == commands[0]
        puts(Time.now)
    end 

    if command == commands[1]
        exit
    end

    if command == commands[3]
        puts(commands)
    end


    #chat
    if command == commands[2]
        system 'cls'
        puts("Hello " + UserName)
    end

    #pauses system
    sleep 10
    puts("Do you want to continue?")
    Response = get.chomp()
    if Response == "yes"
        (rerun program here)
    end

    if Response == "no"
        exit
    end

谢谢

2 个答案:

答案 0 :(得分:0)

最常见的方法是在循环中运行所有内容。我假设您希望每次都重新运行代码。我还为你重构了一个转换声明。

command = gets.chomp.downcase
until command == "no"
    case command
    when command[0]
        puts Time.now
    when command[1]
        exit
    when command[2]
        system 'cls'
        puts("Hello " + UserName)
    when command[3]
        puts commands
    end
end

如果您不想每次都重新运行代码,我会将您想要重新运行的代码放在函数中。

def repeat
    command = gets.chomp.downcase
    case command
    when command[0]
        puts Time.now
    when command[1]
        exit
    when command[2]
        system 'cls'
        puts("Hello " + UserName)
    when command[3]
        puts commands
    when "no"
        repeat
    end
end

答案 1 :(得分:0)

请参阅,您可以将响应放在while循环中并保持继续,直到Response变量的值为yes。

require './codes/AlName.rb'
require './codes/UserName.rb'

system 'cls'

Response = 'yes'
commands = %w(time done chat help)

 while(Response != 'No'){
  command = gets.chomp

  puts Time.now if commands.include?('time')
  exit if commands.include?('done')
  puts commands if commands.include?('help')

  if commands.include?('chat')
    system('cls')
    puts "Hello #{UserName}" #take this as input
  end

  sleep 10 
  Response = get.chomp
  exit if Response == 'no'
 }