2

Suppose I have this :

item_one = Object.find(1) rescue item_one, value = [Object.first, true]

This actually does not work. It returns this :

syntax error, unexpected '=', expecting $end

Does anyone know how to syntactically put multiple assignment in rescue modifier?

Side note:

Boris recommend setting up rescue statements this way :

begin
  i1 = Object.find 1
rescue NoMethodError
  i1, v = Object.first, true 
end
Holger Just
  • 52,918
  • 14
  • 115
  • 123
Trip
  • 26,756
  • 46
  • 158
  • 277
  • I am a huge fan of making the Ruby lines long, but rescue one-liner is really really only for the very simplest situations. – Boris Stitnicky Oct 12 '12 at 16:47
  • @BorisStitnicky What would you recommend alternatively? – Trip Oct 12 '12 at 16:50
  • 1
    Multiline rescue: `begin i1 = Object.find 1; rescue NoMethodError; i1, v = Object.first, true end`. It removes the syntactic ambiguity and gives you a huge advantage of specifying which error you want to rescue. Trust me, oneliner `rescue` is just a very unhealthy syntactic candy, be sure to use them very sparingly. – Boris Stitnicky Oct 12 '12 at 17:24

1 Answers1

3

Use parenthesis. So you are rescuing from the assignment:

(item_one = Object.find(1)) rescue item_one, value = [Object.first, true]
Aaron K
  • 6,901
  • 3
  • 34
  • 29
  • Touché, that makes it so `item_one` represents the array for both `item_one` and `value` – Trip Oct 12 '12 at 16:32