views:

71

answers:

2

I'd like to do something like this in ruby:

safe_variable = begin
  potentially_nil_variable.foo
rescue
  some_other_safe_value
end

... and treat the exception block (begin/rescue/end) as a function/block. This doesn't work as written, but is there a way to get a similar result?

NB what I'm actually doing is this, which works but is IMO ugly:

begin
  safe_variable = potentially_nil_variable.foo
rescue
  safe_variable = some_other_safe_value
end

UPDATE

I guess I hit a corner case on ruby syntax. What I actually was doing was this:

object_safe = begin potentially_nil_variable.foo
rescue ""
end

The error was class or module required for rescue clause. Probably it thought that "" was supposed to be the placeholder for the exception result.

+6  A: 

The form you have should work:

safe_variable = begin
  potentially_nil_variable.foo
rescue
  some_other_safe_value
end

A shorter form:

safe_variable = this_might_raise rescue some_other_safe_value

If you're only avoiding nil, you can look into ActiveRecord's try:

safe_variable = potentially_nil_variable.try(:foo) || some_other_safe_value
Marc-André Lafortune
A: 

The most functional approach I know of for sending a message to an object that might be nil is something like andand. For nil, andand returns an object that will simply return nil no matter what message you send it. For other objects, it returns the original object. And pretty much anything will be more efficient than mucking around with exceptions.

Chuck