Forum: Ruby Keypressed in Ruby

Posted by Kamil G. (kamil_g)
on 2012-11-23 05:08
Hello. I have a small problem with Ruby. I am newbie in rubby and i need
to write something who works like this.


if keypressed = somekey
   do something

i tried to do it using Curses but getch function is waiting everytime
for
key and i don't want that. I want program to work independently from key
pressing unless the right key is pressed. Any tips for me?


def sitemonitor()
    Curses.noecho
    Curses.init_screen
    while true
      puts Curses.getch()
      for i in @listofSite
        if i.updatecheck()
          printf("some msg")
        end
      end
    end
end
Posted by Carlo E. Prelz (Guest)
on 2012-11-23 07:19
(Received via mailing list)
Subject: Keypressed in Ruby
  Date: Fri 23 Nov 12 01:08:33PM +0900

Quoting Kamil G. (lists@ruby-forum.com):

> i tried to do it using Curses but getch function is waiting everytime
> for
> key and i don't want that. I want program to work independently from key
> pressing unless the right key is pressed. Any tips for me?

With Curses, you have to set the terminal in Cbreak mode, otherwise
you will get data only when a carriage return is pressed. This is
obtained by calling

Curses::cbreak

Then, you may also want getch to be non-blocking. In Curses, this is a
per-window setting - see

ri Curses::Window#nodelay=

To set non-blocking getch for your main window, the instruction to use
is

Curses::stdscr.nodelay=true

Remember to close the screen before exiting the program, with

Curses::close_screen

Hope this helps

Carlo
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.