Exit in Ruby
Here’s an idiomatic Ruby example demonstrating the concept of program exit:
This Ruby script demonstrates how to exit a program with a specific status code. Here’s a breakdown of the code:
We define a
cleanup
method that simulates cleaning up resources. This method is registered withat_exit
to be called when the script exits normally.We use the
exit
method to immediately terminate the program with a status code of 3. This is similar to theos.Exit(3)
call in the original Go example.The
puts
statement after theexit
call will never be executed, demonstrating thatexit
immediately terminates the program.
To run this Ruby script:
To check the exit status:
Note that the cleanup method is not called when using exit
. This is similar to how defer
statements are not executed in the Go example.
If you want to ensure that cleanup code is always executed, even when calling exit
, you can use Kernel#at_exit
:
In Ruby, unlike C or Go, you don’t need to explicitly return an integer from the main program to indicate the exit status. The exit
method (or Kernel#exit
) is used to terminate the program with a specific status code.
This example demonstrates how Ruby handles program termination and exit statuses, which is conceptually similar to the Go example but implemented in a Ruby-idiomatic way.