Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a Ruby block/command silently fail without a blank 'rescue' block

Tags:

syntax

ruby

Say I want a call to be run, and if it fails, it's no big deal; the program can continue without a problem. (I know that this is generally bad practice, but imagine a hypothetical, quick one-off script, and not a large project)

The way I've been taught to do this was:

begin
  thing_to_try
rescue
  # awkward blank rescue block
end
next_thing

Of course, there are other ways to do this, including using ensure and things like that. But is there a way to get a method call/block to silently fail without a messy blank block?

like image 964
Justin L. Avatar asked Sep 08 '10 22:09

Justin L.


People also ask

How do you rescue in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.

Can we use rescue without begin?

The method definition itself does the work of begin , so you can omit it. You can also do this with blocks. Now, there is one more way to use the rescue keyword without begin .


2 Answers

It's the same idea, but a little less verbose, but you can use inline syntax

thing_to_try rescue nil
next_thing
like image 134
Ben Hughes Avatar answered Sep 21 '22 16:09

Ben Hughes


A method like this can be helpful.

def squelch(exception_to_ignore = StandardError, default_value = nil)
  yield
rescue Exception => e
  raise unless e.is_a?(exception_to_ignore)
  default_value
end

You might define this method inside class Object for universal availability.

Then you can write:

squelch { foo } || squelch { bar }

The real advantage to having this approach is you can use multiline blocks, since inline rescue can only be used on a single statement.

like image 32
wuputah Avatar answered Sep 22 '22 16:09

wuputah