1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

'rubygems/user_interaction' を使うと、外部 Gem 無しで簡単なプロンプト UI を実装できる

Last updated at Posted at 2024-07-31

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-promptcli-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"
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?