A
aalfred
I've recently had to deal with lots of assignments, where most of them
looked
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
'unless')
Then, while doing some refactoring of the code (and while searching
for
more idiomatic form to gain some more clarity in the code) I rewrote
those as:
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
that these
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
anymore, and
they do not map clearly into: "foo <op>= bar 'stands for' foo = foo
<op> bar".
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 it,
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!
looked
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
'unless')
Then, while doing some refactoring of the code (and while searching
for
more idiomatic form to gain some more clarity in the code) I rewrote
those as:
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
that these
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
anymore, and
they do not map clearly into: "foo <op>= bar 'stands for' foo = foo
<op> bar".
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 it,
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!