Re: Near enough to Python, then.
But for purposes of this example, that's not what's being done.Actually, it is. The Perl and Python examples (1) close the socket (if it is open), (2) print a simple error message, (3) and exit with an error code.
The Ruby version handles (1) within the open method automatically, and (2) and (3) in the top level exception handler provided by Ruby.
If you
want a more custom error message than is provided by the default error handler, or if you want a more specific error code on exit, you could do:
\nbegin\n TCPSocket.open(host, port) do |sock|\n sock.puts(string)\n puts sock.gets\n end\nrescue Exception => ex\n puts "Error: #{ex} at #{ex.backtrace[0]}"\n exit(1)\nend\n
Note that it is not necessary to explicitly close the socket, even in the presence of exceptions, when using the block form of open as coded in the examples.
Error output from original code:
\nrnet.rb:10:in `initialize': Connection refused - connect(2) (Errno::ECONNREFUSED)\n\tfrom rnet.rb:10:in `open'\n\tfrom rnet.rb:10\n
Error output from the modified code above:
\nError: Connection refused - connect(2) at rnet2.rb:11:in `initialize'\n