X a, b = b, a : a, b = a + 1, b + 1

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?

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 )

x ? (a,b = b,a) : (a,b = a+1, b+1)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs