user2026920
user2026920

Reputation: 47

how to make clean if-else + return value

When coding in Ruby, I frequently write something like this

  def someopp(param)
    r_val = nil
    begin
      r_val  = do_something(param)
    rescue Some::Error => e
      r_val  = {} 
    end
    r_val 
  end

I don't like the looks of it. Declaring the return variable that doesn't really do anything, then a line again with just the var name in order to return it. It's cumbersome. I feel that, in Ruby, there must be way to make it more clean and pretty. Any suggestion for syntactic sugar over here?

Upvotes: 1

Views: 288

Answers (2)

Kache
Kache

Reputation: 16667

If you're really doing this exact thing very frequently (calling external dependencies that can raise exceptions and falling back to some default value), can generalize further:

def rescuing(*exceptions, with:)
  yield
rescue *exceptions
  with
end

value = rescuing(ZeroDivisionError, with: Float::INFINITY) { 3 / 0 }
# => Infinity

Though it would be better still if you could avoid the exceptions to begin with, if possible.

Upvotes: 0

spike 王建
spike 王建

Reputation: 1714

def someopp(param)
  do_something(param)
rescue Some::Error
  {} 
end

or

def someopp(param)
  do_something(param) rescue {}
end

But not recomend to use inline-rescue!

Upvotes: 7

Related Questions