Forum: Ruby x a, b = b, a : a, b = a + 1, b + 1

8e16f7669af5b4ecfa4f2b89f32b21b6?d=identicon&s=25 Stefan Salewski (Guest)
on 2013-11-06 14:46
(Received via mailing list)
irb(main):002:0> a = 1; b = 2; x = true # Ruby 1.9.3

irb(main):022:0* if x then  a, b = b, a else  a, b = a + 1, b + 1 end
=> [2, 1]
irb(main):023:0> x ? a, b = b, a : a, b = a + 1, b + 1
SyntaxError: (irb):23: syntax error, unexpected ',', expecting ':'
x ? a, b = b, a : a, b = a + 1, b + 1
      ^
(irb):23: syntax error, unexpected ':', expecting $end
x ? a, b = b, a : a, b = a + 1, b + 1
                 ^

Have I to use the extended if form for such type of assignment, or is
there a way to rewrite the ? : form?
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2013-11-06 14:55
You just need to avoid ambiguous code layout. Don't let Ruby's sweet
syntax make you lazy.

x ? ( a, b = b, a ) : ( a, b = a + 1, b + 1 )
B55d9706b57e8d286a4f198daf2ac69c?d=identicon&s=25 Andrea Dallera (edwin_bolthar)
on 2013-11-06 14:57
(Received via mailing list)
x ? (a,b = b,a) : (a,b = a+1, b+1)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.