James Stewart James Stewart - 3 years ago 186
Ruby Question

Multiple choice quiz in Ruby via Terminal

I don't know if Terminal allows for this, but is there any way to Ruby code the terminal to present two options which requires the user to select using the arrow keys and confirm using Enter?

Pseudo code:

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


I'm interested to know if this can be achieved without the user having to type in their answer? Can the Terminal behave like a GUI?

Answer Source

You could use something like Highline, though that will not let you use arrow keys:

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

Code (just to get an idea):

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

For more of a GUI, try using something like MRDialog.

Example:

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}"

Result:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download