FrozenHeart
FrozenHeart

Reputation: 20746

How to properly work with Curses::KEY_BACKSPACE in Ruby

Suppose that I have the following code:

require 'curses'

Curses.init_screen

loop {
  ch = Curses.getch
  case ch
    when Curses::KEY_BACKSPACE
      Curses.addstr('Backspace \n')
    else
      Curses.addstr("Key: #{ch} \n")
  end
}

Curses.close_screen

When I press the backspace key, I get the following output:

Key: 8

Expected output:

Backspace

Why? What am I doing wrong? How can I fix it?

Thanks in advance.

Upvotes: 0

Views: 399

Answers (1)

William McBrine
William McBrine

Reputation: 2256

You're not doing anything wrong. The problem is the definition of KEY_BACKSPACE, vs. what the terminal actually returns... it's a historical mess, basically.

Just check for \b (or 8) instead of, or in addition to, KEY_BACKSPACE. (I'm not sure you'll ever get a returned value of KEY_BACKSPACE, in practice, but it's harmless enough to check for it.)

Upvotes: 2

Related Questions