RubyGems 内には、 rubygems/user_interaction
という (RubyGems 用の) プロンプト UI を実装するためのヘルパーがあります。
require 'rubygems/user_interaction' # 標準ライブラリなので、これ自体のインストールは不要
ui = Gem::ConsoleUI.new
ui.ask('What is your name?')
# What is your name? tomoasleep
# => "tomoasleep"
ui.ask_yes_no('Are you ok?')
# Are you ok? [yn] y
# => true
ui.ask_yes_no('Are you ok?', true)
# Are you ok? [Yn]
# => true
ui.choose_from_list('What is your favorite food?', ['ramen', 'sushi', 'tempura'])
# What is your favorite food?
# 1. ramen
# 2. sushi
# 3. tempura
#
# > 1
# => ["ramen", 0]
# > 2
# => ["sushi", 1]
RubyGems 内での利用を想定しているので、基本的には tty-prompt や cli-ui などの gem を使う方が安定していて良いと思いますが、使い捨てのコードで gem をどうしてもインストールしたくない場合は覚えておくと良いかも知れません。
おまけ: tty-prompt を使う場合
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'tty-prompt'
end
prompt = TTY::Prompt.new
prompt.ask('What is your name?')
# What is your name? tomoasleep
# => "tomoasleep"
prompt.yes?('Are you ok?')
# Are you ok? (Y/n)
# => true
prompt.select('What is your favorite food?', ['ramen', 'sushi', 'tempura'])
# What is your favorite food? (Press ↑/↓ arrow to move and Enter to select)
# ‣ ramen
# sushi
# tempura
# => "ramen"
おまけ2: cli-ui を使う場合
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'cli-ui'
end
# または、
# require 'cli/ui'
CLI::UI.ask('What is your name?')
# ? What is your name?
# > tomoasleep
# => "tomoasleep"
CLI::UI.confirm('Are you ok?')
# ? Are you ok? (Choose with ↑ ↓ ⏎)
# > 1. yes
# 2. no
#
# ? Are you ok? (You chose: yes)
# => true
CLI::UI.ask('What is your favorite food?', options: ['ramen', 'sushi', 'tempura'])
# ? What is your favorite food? (Choose with ↑ ↓ ⏎, filter with 'f')
# > 1. ramen
# 2. sushi
# 3. tempura
#
# ? What is your favorite food? (You chose: ramen)
# => "ramen"