CTRL + C in the ruby Console

Source: Internet
Author: User

When developing a ruby console application in Ruby, you may encounter a problem: You can use Ctrl + C to stop the running program.

If no control is added, the program is aborted and an error stack is printed.

For example, the following program:

Cmd = Nil
While cmd !~ /Y | n | N/
Print "continue? (Y/N ):"
Cmd = stdin. Gets
Cmd. chomp!
End
If cmd = ~ /Y | Y/then
Puts "continue ."
Else
Puts "exit ."
End

When running, CTRL + C is interrupted, the screen displays:

Continue? (Y/N): e:/projectruby/03 _ Getting Started without opening/06_source/testru
Nner/tester. RB: 48: In 'gets': interrupt
From E:/projectruby/03 _ Getting Started without opening/06_source/testrunn
ER/tester. RB: 48

In order to prevent the interruption information from causing bad prompts to users, the program should handle this situation,

The user's Ctrl + C will throw an interrupt exception at the ruby underlying layer, so you can capture this exception through begin... rescue... end.

Begin
Cmd = Nil
While cmd !~ /Y | n | N/
Print "continue? (Y/N ):"
Cmd = stdin. Gets
Cmd. chomp!
End
If cmd = ~ /Y | Y/then
Puts "continue ."
Else
Puts "exit ."
End
Rescue interrupt
Puts "programme is interrupted ."
End

When running, CTRL + C is interrupted, the screen displays:

Continue? (Y/N): Programme is interrupted.

This prevents user confusion caused by stack information.

The PS: kernal: exit command throws a systemexit exception.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.