Today I Learned

hashrocket A Hashrocket project

Ruby's Abbreviated Assignment Operators

Today I Learned ruby has a lot of abbreviated assignment operators.

The best known are += and -= to increment and decrement values:

x = 2
x += 1
x #=> 3

And of course there's ||=, to assign only if the value is nil or false:

x = nil
x ||= 4 #=> 4
x ||= 5 #=> 4

But these abbreviations can be applied to a lot more operators!

It works with all of the following: +, -, *, /, %, **, &, |, ^, <<, >>, &&, ||.

So we could use |= to union two arrays and assign the result to the variable:

x = [1, 2, 3]
x |= [2, 3, 4, 4]
x #=> [1, 2, 3, 4]
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.