'What will give me something like ruby readline with a default value?

If I want to have a prompt on the terminal with a default value already typed in, how can I do that?

Ruby's standard Readline.readline() lets me set the history but not fill in a default value (as far as I can tell, at least)

I would like something like this:

code:

input = Readline.readline_with_default('>', 'default_text')

console:

> default_text|


Solution 1:[1]

What you are asking is possible with Readline. There's a callback where you can get control after the prompt is displayed and insert some text into the read buffer.

This worked for me:

Readline.pre_input_hook = -> do
  Readline.insert_text "hello.txt"
  Readline.redisplay

  # Remove the hook right away.
  Readline.pre_input_hook = nil
end

input = Readline.readline("Filename: ", false)
puts "-- input:#{input.inspect}"

BTW, I fairly tried to use HighLine, but it appeared to be a no-alternative to me. One of the disappointing reasons was the fact that HighLine#ask reads cursor movement keys as regular input. I stopped looking in that direction after that sort of discovery.

Solution 2:[2]

+1 to highline

try with something like:

require 'highline/import'
input = ask('> ') {|q| q.default = 'default_text'} # > |default_text|

Solution 3:[3]

Sounds like a job for ncurses. Seems like rbcurse (http://rbcurse.rubyforge.org/) is the best maintained API at the moment.

Solution 4:[4]

I'm struggling with the same thing.

The way I'm doing it right now is:

options = ["the_text_you_want"]
question = "use TAB or up arrow to show the text > "

Readline.completion_append_character = " "
Readline::HISTORY.push options.first
Readline.completion_proc = proc { |s| options.grep( /^#{Regexp.escape(s)}/ ) }

while value = Readline.readline(question, true)
  exit if value == 'q'
  puts value.chomp.strip #do something with the value here
end

yes, it's silly, but it has been the only way I've found to do it.

did anybody find any solution to this?

Solution 5:[5]

Highline doesn't do exactly what you describe, but maybe it's close enough.

Solution 6:[6]

New answer to an old question, but adding because I found this looking for an answer to the same question.

tty-prompt looks like it does what you are looking for - asking for input with an editable default. It's the only gem I found that would give me the editable default (but there may be others)

Full code to to that would look like:

require "tty-prompt"
prompt = TTY::Prompt.new
input = prompt.ask('What is your name?', value: 'Bob')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 raf
Solution 5 Ken Liu
Solution 6 Jon Howard