format internet:

…please wait (42% completed)…

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.

2 Responses to “Parallel Assignment in Ruby and the conditional ternary operator”

  1. Millard said

    You share interesting things here. I think that your website can go viral easily, but you must give it initial boost and i know how to do it,
    just search in google (with quotes) for –
    “mundillo traffic increase make your website go viral”

  2. sfsdfsdfsd said

    A ja to bym chciała przetestowac krem do loków-cokolwiek by tonie było.Chciałabym zobaczyć moja córcie w piękny loczkach. Kocham jej włosy,ciesze się z każdego ich centymetra i nie pozwoliłabym ich zniszyć.Ale chciałabym ją zobaczyc,(chociaz raz) w pięknych loczkach w tą Wielkanoc.Tym bardziej że ja często sobie kręce a córcia tylko patrzy z zazdrością.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: