I’ve recently had to deal with lots of assignments, where most of them
like those two lines:
foo = bar if !bar.nil? # (case 1) or
foo = bar if foo.nil? && !bar.nil? # (case 2)
(I know it could be written using ‘unless’, but I strongly dislike
Then, while doing some refactoring of the code (and while searching
more idiomatic form to gain some more clarity in the code) I rewrote
foo ??= bar # case 1
foo !!= bar # case 2
At the end it turned out there were only those two cases:
- case 1: ‘do-not-assign-nil’, and
- case 2: ‘do-not-assign-nil’ for ‘||=’ (similarity with !!=)
I thought I ‘discovered’ new fine operators! But I later found out
cannot be new operators, but are just a possible syntatic sugar.
If you cannot understand those two lines quick, they are probably
useless. And I
admit that after rethinking they were not so simple to understand
they do not map clearly into: “foo = bar ‘stands for’ foo = foo
But the code still looked ‘cute’ (or at least more ‘clean’) to me!
And so I decided to post it just as a question of what others think
about how often they would use it, and if anyone likes it at all.
This is not a proposal to sweeten the (already sweet) ruby syntax!