Today, while working on consuming a third-party API, I discovered that the result of a begin/rescue/end block in Ruby can assign to a variable, just like an if statement can.

This isn’t a technique I’d recommend for every single situation where it could be used, but it is convenient for operations where a particular error scenario can result in a single return value.

Here’s an example of reading a remote file and assigning it to an object. If the file operation fails (in this case, if the HTTP request fails with anything other than a 2xx or 3xx status), a fallback value is assigned instead:

require "ostruct"
require "open-uri"

model =
model.title = begin
rescue OpenURI::HTTPError
  "Default Title"

puts model.title
# => This is a title from a remote file