Ruby’s assign if not nil operator

I think most Ruby programmers know the ||= operator, where a variable is assigned a value if nil.

For those who don’t know, it works like this.

In the example above, variable a is assigned 1 because it is nil. If a wasn’t nil, 1 wouldn’t be assigned to a and a would just remain nil.

I recently came across the &&= operator while reading Confident Ruby by Avdi Grimm. It basically works like this. It works kind of like the ||= operator except that it assigned a value to a variable if it isn’t nil. An example would be.

I think this is a good way to make your code concise by getting rid of a lot of if statements. For example, I do this a lot in my code.

That if statement above can be replaced with &&=, making our code more concise.

This is a short post, just sharing something new I’ve learned in the past few days.