3

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")

Binyuan Sun
  • 146
  • 1
  • 9
  • it's surprisingly difficult question. Either do `File.read` and `File.write` with `gets.chomp` or just use the regular text editor ... – max pleaner Aug 20 '16 at 07:24

2 Answers2

0

I would use vim to edit the file. Vim will save edited files in ~/.viminfo. The last edited file is marked with '0. The pattern of a file entry is 'N N N filename where N stands for a integer.

def editableprint(filename)
  system "vi #{filename}"
  regex = /(?<='0\s{2}\d\s{2}\d\s{2}).*/
  viminfo = File.expand_path("~/.viminfo")
  File.read(viminfo).scan(regex).first
end

In order to make this to work you would have to change your code

print("Enter a filename:")
filename = gets.chomp!
filename = "untitled.txt" if filename.emtpy?
edited_filename = editableprint("untitled.txt")
sugaryourcoffee
  • 879
  • 8
  • 14
0

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}"
Community
  • 1
  • 1
Kjell
  • 492
  • 1
  • 7
  • 15