How to Capture Terminal Arrow Keys in Ruby

How can I capture terminal arrow keys in Ruby?

Look into the Ruby console libraries ruby-termios
and ncurses-ruby.

Creating arrow key navigation in a command line application?

Ruby Toolbox is a great resource for finding gems that you can use, the link here pointing toward the search for 'curses'.

ncurses should work with any ANSI/Posix compliant system.

Backspace and arrow keys aren't working in IRB(Git Bash console) on windows machine

Same thing happened to me. Running irb with --noreadline solved my problem:

irb --noreadline

Arrow keys don't work in irb/ruby command line scripts?

Using Ruby's Readline Library:

require 'readline'
foo = Readline::readline

How to allow users to edit given string via $stdin in ruby

begin
system("stty raw -echo")
print (acc = "Edit me: ")
loop.each_with_object(acc) do |_,acc|
sym = $stdin.getc
case sym.ord
when 13 # carriage return
break acc
when 127 # backspace
print "\e[1D \e[1D"
acc.slice!(acc.length - 1) if acc.length > 0
else # regular symbol
print sym
acc << sym
end
end
ensure
system("stty -raw echo")
puts
puts "\e[0mEntered: |#{acc}|"
end

Here you go. More info on terminal control sequences. Also, ANSI terminal codes.



Related Topics



Leave a reply



Submit