Skip to content

Instantly share code, notes, and snippets.

@botimer
Created June 7, 2012 19:56
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save botimer/2891186 to your computer and use it in GitHub Desktop.
Save botimer/2891186 to your computer and use it in GitHub Desktop.
Handy yes/no prompt for little ruby scripts
# This is a reasonably well-behaved helper for command-line scripts needing to ask a simple yes/no question.
# It optionally accepts a prompt and a default answer that will be returned on enter keypress.
# It keeps asking and echoes the answer on the same line until it gets y/n/Y/N or enter.
# I tried to get Highline to behave like this directly, but even though it's sophisticated, I didn't like the result.
# This isn't especially elegant, but it is straightforward and gets the job done.
require 'highline/import'
def yesno(prompt = 'Continue?', default = true)
a = ''
s = default ? '[Y/n]' : '[y/N]'
d = default ? 'y' : 'n'
until %w[y n].include? a
a = ask("#{prompt} #{s} ") { |q| q.limit = 1; q.case = :downcase }
a = d if a.length == 0
end
a == 'y'
end
puts yesno("Do it?", true)
@mattycourtney
Copy link

I used this instead:

require 'highline/import'
confirm = ask("Do it? [Y/N] ") { |yn| yn.limit = 1, yn.validate = /[yn]/i }
exit unless confirm.downcase == 'y'

@posgarou
Copy link

I don't know if this was in HighLine when the above answers were posted, but this is now even easier:

exit unless HighLine.agree('This will drop the User table. Do you want to proceed?')

The docs for #agree

@lfender6445
Copy link

if you don't want to use highline and your shell supports it, you could also do something like this:

printf "\033[31mWARNING -  press 'y' to continue: "
prompt = STDIN.gets.chomp
return unless prompt == 'y'

@matkoniecz
Copy link

@lfender6445 This red colour thing is buggy - it is not ended properly. At least on Linux, on interupted/crashed progams it will stay in terminal (untested in other situations).

@HK49
Copy link

HK49 commented Feb 3, 2017

@matkoniecz, cause format wasn't cleared. For those to come:
The printf "\033[31mWARNING - press 'y' to continue: "
should be:
The printf "\033[31mWARNING - press 'y' to continue: \033[0m"
if you want red color only in the message.

@grosser
Copy link

grosser commented Nov 16, 2017

FYI \e also works as shorthand for \033
printf "\e[31m#{question} - press 'y' to continue: \e[0m"

@tweissin-pillpack
Copy link

You can also just do
puts "press 'y' to continue:".red

@stevenspiel
Copy link

If you do what @tweissin-pillpack suggests, you'll also want to require 'colored'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment