0

I have some code that passes tests in rspec. It appears I don't need end with a double rescue in Ruby, or even begin for that matter. Essentially, I return 5 when a Geocoder error is encountered and 6 if a CustomError is encounted and 7 otherwise.

def get_stuff
  puts "some code work"
  rescue ::Geocoder::Error => e
    puts "hello"
    return 5
  rescue CustomError => e
    puts "world"
    return 6
  7
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Nona
  • 5,302
  • 7
  • 41
  • 79
  • It'd probably help if you read some tutorials about using `rescue`. This is covered as part of all the Ruby books I've seen. – the Tin Man Jan 21 '16 at 23:42
  • Function definitions have an implicit begin block. So the `rescue` is on the `def` block, same as it would be on an explicit `begin` block in other scenarios. As others have mentioned, indentation is meaningless in Ruby. – David Hempy Aug 28 '19 at 18:59

2 Answers2

4

Indentation doesn't matter in Ruby. Technically the 7 will never be returned because you have it inside the rescue block after the return 6 line.

If you want to return 7 when no error is raised, place it on the last line before the rescue blocks:

def get_stuff
  puts "some code work"
  7 #success!
  rescue ::Geocoder::Error => e
    puts "hello"
    return 5
  rescue CustomError => e
    puts "world"
    return 6
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
T J
  • 1,312
  • 7
  • 7
3

A method is its own begin/end block, so you can just do rescue when you need it, and also ensure when you need it.

As you've done, you do need to do explicit return statements if the rescue or ensure block should return a value.

... although I'm surprised that you're getting 7 returned... that's part of your second rescue block and shouldn't return.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53