Print editable to console in Ruby

Binyuan Sun

Let's say I have the following code in Ruby:

print("Enter a filename:")
editableprint("untitled.txt")
filename = gets.chomp!

What would be the function "editableprint" so that "untitled.txt" is part of the input of the user for the gets function? (thus the user can edit the "untitled.txt" string or simply leave it as is")

Kjell

There are similar questions here and here

However, the solutions there don't seem to work as expected, so it looks this is ruby version or platform dependent?

For example, this does not work for me, but also does not throw an error.

require "readline"

filename = Readline.insert_text("untitled.txt").readline("Enter a filename:")
print filename

But since it looks much better, and should work according to the documentation for ruby >= 2, I am leaving it there for now.

The following works on my system (ruby 2.3.1, OS X)

require "readline"
require 'rb-readline'

module RbReadline
  def self.prefill_prompt(str)
    @rl_prefill = str
    @rl_startup_hook = :rl_prefill_hook
  end

  def self.rl_prefill_hook
    rl_insert_text @rl_prefill if @rl_prefill
    @rl_startup_hook = nil
  end
end

RbReadline.prefill_prompt("untitled.txt")
str = Readline.readline("Enter a filename:", true)

puts "You entered: #{str}"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related