This is a very common condition with Ruby code, and a common idiom to return nil
on a failed search.
However this specific gem is a little flaky when it fails to get a good search result. You can protect yourself against it failing by using a begin ... rescue
block.
begin
stock_quote = StockQuote::Stock.quote(@ticker)
rescue StandardError
stock_quote = nil
end
if stock_quote
@companyname = stock_quote.company
@exchange = stock_quote.exchange
@price = stock_quote.last
end
This might not be ideal program flow for you, so you may need to adapt this.
Note StandardError
is what gets rescued by default, I didn't need to write that. You could also put NoMethodError
in your situation, and usually you want to restrict rescuing exceptions to specific parts of code where you know how to recover from the error, and also only to the types of errors where you are confident that your handling code is doing the right thing.