【问题标题】:Ruby Rerun my scriptRuby 重新运行我的脚本
【发布时间】:2015-01-28 17:29:08
【问题描述】:

如果用户要求,我希望我的 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

谢谢

【问题讨论】:

    标签: ruby loops


    【解决方案1】:

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

    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
    

    【讨论】:

    • 谢谢,我不会想到使用 until's
    • 没问题!我相信您将来会遇到设计模式。另外,当我第一次学习 ruby​​ 时使用 untilunless 有点违反直觉,但在编写 ruby​​ 代码一段时间后,它就会成为第二天性。
    【解决方案2】:

    你看,你可以把 Response 放在 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'
     }
    

    【讨论】:

      猜你喜欢
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多