In ruby, I’m not quite sure how to handle whether objects are nil or not.
For example I have the following:
begin
sp = SerialPort.new(@serial_device, @serial_bps, @serial_par, @serial_bits, SerialPort::NONE)
tcp = TCPSocket.new(@host, @port)
if (sp)
sp.print(command)
sp.close
elsif
tcp.print(command)
tcp.close
end
say siri_output
rescue
pp $!
puts "Sorry, I encountered an error: #{$!}"
ensure
request_completed
end
The problem is that the first object returns an error relating to:
No route to host - connect(2)
Which is correct, because TCP isn’t connected duh. So I’d like it to use the next object instead.
Is there a way to do this without using certain Exceptions, I was wondering if there’s a better way of doing what I’m after any how.
The problem is not the checks, you are doing that right. Anything that’s not nil or false is true in ruby. It’s that when you get an exception on the row that starts with “sp = ..” the execution jumps to the resque block. You should restructure the code like this (I’ve removed the ensure clause because I do not know what it does). A good thing to do it’s to rescue every specific type of exception in it’s own row. by class name ex. NoConnectivityException => e (or what the class of the exception would be).
For quick and sloppy programming you can do another thing, but it’s not recommended and generally a pain to debug, as any error results in nil and is silenced.
This way you’d end up with either a SerialPort object or nil object in the sp variable, and the same for sp.