Flowdock
method

readline

Importance_2
readline(p1 = v1, p2 = v2) public

Shows the prompt and reads the inputted line with line editing. The inputted line is added to the history if add_hist is true.

Returns nil when the inputted line is empty and user inputs EOF (Presses ^D on UNIX).

Raises IOError exception if below conditions are satisfied.

  1. stdin is not tty.

  2. stdin was closed. (errno is EBADF after called isatty(2).)

This method supports thread. Switchs the thread context when waits inputting line.

Supports line edit when inputs line. Provides VI and Emacs editing mode. Default is Emacs editing mode.

NOTE: Terminates ruby interpreter and does not return the terminal status after user pressed ā€˜^Cā€™ when wait inputting line. Give 3 examples that avoid it.

  • Catches the Interrupt exception by pressed ^C after returns

terminal status:

  require "readline"

  stty_save = `stty -g`.chomp
  begin
    while buf = Readline.readline
        p buf
        end
      rescue Interrupt
        system("stty", stty_save)
        exit
      end
    end
  end
  • Catches the INT signal by pressed ^C after returns terminal

status:

  require "readline"

  stty_save = `stty -g`.chomp
  trap("INT") { system "stty", stty_save; exit }

  while buf = Readline.readline
    p buf
  end
  • Ignores pressing ^C:

    require "readline"
    
    trap("INT", "SIG_IGN")
    
    while buf = Readline.readline
      p buf
    end
    

Can make as follows with Readline::HISTORY constant. It does not record to the history if the inputted line is empty or the same it as last one.

require "readline"

while buf = Readline.readline("> ", true)
  # p Readline::HISTORY.to_a
  Readline::HISTORY.pop if /^\s*$/ =~ buf

  begin
    if Readline::HISTORY[Readline::HISTORY.length-2] == buf
      Readline::HISTORY.pop
    end
  rescue IndexError
  end

  # p Readline::HISTORY.to_a
  print "-> ", buf, "\n"
end

Raises SecurityError exception if $SAFE is 4.

Show source
Register or log in to add new notes.