Exit in Ruby
Here’s an idiomatic Ruby example demonstrating the concept of program exit:
# exit_example.rb
# This method will not be executed due to the early exit
def cleanup
puts "Cleaning up resources..."
end
# Register the cleanup method to be called when the script exits normally
at_exit { cleanup }
puts "Starting the program"
# Exit the program with status code 3
exit(3)
# This line will never be reached
puts "This won't be printed"This Ruby script demonstrates how to exit a program with a specific status code. Here’s a breakdown of the code:
We define a
cleanupmethod that simulates cleaning up resources. This method is registered withat_exitto be called when the script exits normally.We use the
exitmethod 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
putsstatement after theexitcall will never be executed, demonstrating thatexitimmediately terminates the program.
To run this Ruby script:
$ ruby exit_example.rb
Starting the programTo check the exit status:
$ echo $?
3Note 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:
at_exit do
puts "This will be printed even when using exit"
end
exit(3)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.