tags:

views:

71

answers:

3

Hi there,

What's Ruby for the following?

if executing the next line wouldn't cause any kind of error then
  execute this line
elsif executing the next line wouldn't cause any kind of error then
  execute this line
else

I've been reading the API pages for rescue and exceptions and eval but so far have failed in my quest.

Many thanks,

Steven.

+1  A: 

I'll rename your pseudocode to clarify:

if lineA doesn't cause an error
  execute lineA
elsif lineB doesn't cause an error
  execute lineB
end

Is this right in the way you wanted it? Then why not use

begin
  lineA
rescue
  error_handling
ensure
  lineB
end

If you want to do more of this you can nest it and for sure it's a good idea to refactor some new methods out of it.

Alternativly the shorthand:

valA = lineA rescue StandardError
lineB if valA.is_a?(Exception)

And of course you can repeat this as many times as you'd like to! ;)

Joe
Thanks Xijo. Yes, your rewritten pseudocode capture my intention, so I'll have a crack at working your Ruby code into mine. Thanks again.
steven_noble
the begin...ensure does lineA and lineB, but the shorthand fixes that.
rampion
A: 

Following on from a comment from Assaf Arkin, I'm going to suggest the following syntax:

if first_condition
 execute_this_line rescue nil
elsif second_condition
 execute_that_line rescue nil
end

Will the result be as follows?

If first_condition is true and it's possible to execute_this_line without error, then it will execute_this_line.

If first_condition is true and execute_this_line normally generates an error, it will jump to end.

If first-condition is false, it will test second_condition.

If second_condition is true and it's possible to execute_that_line without error, then it will execute_that_line.

Otherwise it will jump to end.

steven_noble
This is a question-and-answer site, not a general discussion forum. You posted this as an answer, but it is not an answer to your question. If you want to add to your question, just add to it.
Chuck
A: 

Actually, I think I need:

if first_condition rescue nil
 execute_this_line
elsif second_condition rescue nil
 execute_that_line
end

Will the result be as follows?

If first_condition is true, then it will execute_this_line.

If first_condition is false or generates an error, it will jump to second_condition without action throwing an error.

etc...

steven_noble