【问题标题】:Multiple choice quiz in Ruby via terminal通过终端在 Ruby 中进行多项选择测验
【发布时间】:2017-09-30 10:10:38
【问题描述】:

有没有办法在 Ruby 中进行编码,以便终端显示两个选项,用户需要使用箭头键选择并使用 Enter 确认?

伪代码:

p "What is the capital of Scotland? 
user_select = gets.chomp
p "Edinburgh" 
p "Glasgow"
if user_select == "Edinburgh" etc etc

我想知道这是否可以在用户无需输入答案的情况下实现。终端可以像 GUI 一样工作吗?

【问题讨论】:

    标签: ruby terminal


    【解决方案1】:

    或者,您可以使用 TTY::Prompt。它会让你使用箭头键。

    代码示例

    require 'tty-prompt'
    
    prompt = TTY::Prompt.new
    greeting = 'What is the capital of Scotland?'
    choices = %w(Edinburgh Glasgow)
    answer = prompt.select(greeting, choices)
    'do something' if answer == choices[0]
    

    结果

    $ ruby quiz.rb
    
    What is the capital of Scotland? (Use arrow keys, press Enter to select)
    ‣ Edinburgh
      Glasgow
    

    【讨论】:

    • 嗨 NikK,除了 tty-prompt 之外,我还需要 gem install 吗?它不让我使用箭头键,它只是显示为:苏格兰的首都是什么? ‣ 爱丁堡,格拉斯哥
    • 嗨詹姆斯!除了 tty-prompt,你不需要安装任何东西。我在 %w 符号中打错了字。我更新了答案,请重试。
    【解决方案2】:

    您可以使用Highline 之类的东西,尽管这不会让您使用箭头键:

    → ruby test.rb
    1. Edinburgh
    2. Glasgow
    What is the capital of Scotland?
    → 1
    Correct! 
    

    代码(仅供参考):

    require 'highline'
    
    cli = HighLine.new
    
    cli.choose do |menu|
      menu.prompt = "What is the capital of Scotland?"
      menu.choice("Edinburgh") { cli.say "Correct!" }
      menu.choice("Glasgow") { cli.say "Wrong!" }
    end
    

    如需更多 GUI,请尝试使用 MRDialog 之类的内容。

    例子:

    require 'mrdialog'
    
    dialog = MRDialog.new
    dialog.clear = true
    dialog.title = "Quiz"
    
    question = "What is the capital of Scotland?"
    answers = [['E', 'Edinburg'], ['G', 'Glasgow']]
    
    height = 0
    width = 0
    menu_height = 2
    
    selected_item = dialog.menu(question, answers, height, width, menu_height)
    
    puts "Selected item: #{selected_item}"
    

    结果:

    【讨论】:

    • 谢谢!这很有帮助:)
    • 在这种情况下,您应该投票和/或接受答案(花点时间接受它,看看其他人怎么说,我只是想解释基本的 StackOverflow 礼仪)。
    • 我投了赞成票,但恐怕我的声望不够高,无法计算
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多