I have this program:
5.times do |i|
puts "Iteration #{i}"
system("sleep 3")
end
I want to exit this program after, say 2 iterations, usin Ctrl-C
If I hit Ctrl-C, this happens:
➜ tmp ruby system.rb
Iteration 0
^CIteration 1
^CIteration 2
^CIteration 3
^CIteration 4
^C%
The system() command is run 5 times, no matter what.
What can I do so that I’m able to quit the execution using Ctrl-C?
Kernel#systemexecutes a given command in a sub-shell. Which means that Ctrl-C is going to that subshell and not your ruby script, so there’s no use trapping it there. However, the command returns a value which indicates, whether it was completed successfully or not. When the command is stopped via Ctrl-C, it won’t count as a successful completion. So, check the return value.