LoginSignup
16
17

More than 5 years have passed since last update.

HighLine を使って Ruby で簡単に対話型のアプリケーションを作る

Last updated at Posted at 2016-01-02

対話型のアプリケーションを作るのにとてもお手軽だったので、HighLine をご紹介

使い方

gem install highline

でインストールして、HighLine#ask を呼ぶだけ

require 'highline'

cli = HighLine.new
name = cli.ask("What's you name?")
puts "You are #{name}"


#=> What's you name?
#<= pekepek
#=> You are pekepek

できた!

他にも

デフォルト値の設定

cli = HighLine.new
name = cli.ask("What's you name?") {|q| q.default = 'taro' }
puts "You are #{name}"

#=> What's you name?  |taro|
#<=
#=> You are taro

入力のマスク

cli = HighLine.new
name = cli.ask("What's you name?") {|q| q.echo = false }
puts "You are #{name}"

#=> What's you name?
#<=
#=> You are pekepek
cli = HighLine.new
name = cli.ask("What's you name?") {|q| q.echo = 'x' }
puts "You are #{name}"

#=> What's you name?
#<= xxxxxxx
#=> You are pekepek

選択肢の表示

cli = HighLine.new
cli.choose do |menu|
  menu.prompt = "What's you name?"
  menu.choice(:pekepek) { cli.say('Correct!!') }
  menu.choices(:pokopok, :pukupuk) { cli.say('Wrong') }
end

#=> 1. pekepek
#=> 2. pokopok
#=> 3. pukupuk
#=> What's you name?
#<= 1
#=> Correct!!

ERB を使った出力

cli = HighLine.new
name = cli.ask("What's you name?")
cli.say("You are <%= color('#{name}', :bold, :blue) %>")

image

validation

cli.ask("What's you name?") {|q| q.validate = /\Ap*\z/ }

#=> What's you name?
#=< pekepek
#=> Your answer isn't valid (must match /\Ap*\z/).
#<=?  ppp
#=> You are ppp

文字数制限

cli.ask("What's you name?") {|q| q.limit = 3 }

などなど色々と出来る

試しに

適当なデータを用意して、ユーザーデータを検索・表示するアプリを作ってみる

適当なデータ
name,age,job
yamada taro,40,bankers
sato jiro,30,programmer
takada saburo,20,student
適当なデータを検索するやつ
require 'highline'

f = File.open(ARGV.shift)
items = f.gets.chomp.split(',')
all_data = f.map {|str| str.chomp.split(',') }

cli = HighLine.new

target_data = loop do
  name = cli.ask('誰を検索しますか?')
  data = all_data.find {|data| Regexp.new(name) === data.first }

  if data.nil?
    puts '該当するユーザーはいません'
  else
    break data
  end
end

selected_item = cli.choose do |menu|
  menu.prompt = "欲しい項目を選んで下さい "
  menu.choices(*items)
end

puts target_data[items.index(selected_item)]
#=> 誰を検索しますか?
#<= shiro
#=> 該当するユーザーはいません
#=> 誰を検索しますか?
#<= jiro
#=> 1. name
#=> 2. age
#=> 3. job
#<= 欲しい項目を選んで下さい 3
#=> programmer

簡単!!

16
17
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
16
17