Sunday, June 22, 2014

Multiple Assignments in Ruby

In this Rails project I'm running I need to set a whole bunch of individual variables to 'disabled' at once depending on the group the current user belongs to. We can use multiple assignment in this case but with a caveat.

Multiple assignments are a quick way of setting a lot of variables at once.

h, k = 1,2  => [1,2]

h => 1
k => 2

but 

h, k = 1      => 1

h => 1
k => nil

In that case we can do this:

h = k = 1   => 1

h => 1
h => 1 

Beware this sets them to the same object. So if you change one you change both.

h = k = []
h << 1

h => [1]
k => [1]

While we're at it here is how to reverse two variables:

h = 1
k = 2
h,k = k,h

h => 2
k => 1






No comments:

Post a Comment