Parallel Assignment in Ruby and the conditional ternary operator
Posted by javier ramirez on April 8, 2009
You already know how parallel assignment in Ruby works
irb(main):001:0> a,b=1,2 => [1, 2] irb(main):002:0> p a 1 => nil irb(main):003:0> p b 2 => nil
and you also know how the conditional operator (the only ternary operator in Ruby) works.
irb(main):004:0> false ? a : b => 2
so maybe you are thinking of putting that together and, given a “wadusable” object, do something like
wadusable = 'dummy value' wadusable_type, wadusable_id = wadusable ? (wadusable.class.name,wadusable_id) : ('DefaultClass',default_id)
Well.. think twice.. the code above will FAIL.. syntax error. So.. does it mean I cannot mix the ternary operator with parallel assignment in Ruby? Not so fast.. after applying the technique of “Complaining Programming” (you heard it first here!) diego pointed me in the right direction.
Sometimes, I tend to forget Ruby plays pretty nice when there are no ambiguities, and allows us to do certain things like omitting parenthesis when calling a method, or forget about brackets in array literals.
But when there are ambiguities, then Ruby needs to know what we really want. In this case, what I have to do is specifically use brackets around the operator return values, so Ruby can properly make the parallel assignment.
wadusable = 'dummy value' wadusable_type, wadusable_id = wadusable ? [wadusable.class.name,wadusable_id] : ['DefaultClass',default_id]
And that’s it.