# Keypressed in Ruby

**URL:** <https://www.ruby-forum.com/t/keypressed-in-ruby/224719>\
**Category:** Ruby\
**Created:** [November 23, 2012, 5:08am UTC](https://www.ruby-forum.com/t/keypressed-in-ruby/224719 "2012-11-23T05:08:30Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![aris](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/258eb7/32.png) [@aris](https://www.ruby-forum.com/u/aris)\
**Post date:** [November 23, 2012, 5:08am UTC](https://www.ruby-forum.com/t/keypressed-in-ruby/224719/1 "2012-11-23T05:08:30Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![grymuz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/779978/32.png) [@grymuz](https://www.ruby-forum.com/u/grymuz)\
**Post date:** [November 23, 2012, 7:19am UTC](https://www.ruby-forum.com/t/keypressed-in-ruby/224719/2 "2012-11-23T07:19:34Z")

</div>

Subject: Keypressed in Ruby  
Date: Fri 23 Nov 12 01:08:33PM +0900

Quoting Kamil G. ([removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)):

> 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
