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!
On Apr 23, 7:40 pm, aalfred <alfred.anzlo...@gmail.com> wrote:
> 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')
>
I think you won't need your new sugar if you just rewrite the
originals:
foo = bar if bar # case 1
foo ||= bar if bar # case 2
There is a subtelty in the assignment that is hard to see at the first
glance: you *never* assign nil to foo (but assign can false).
So your rewrite is not equivalent.
···
On Apr 24, 5:37 am, Jeff <cohen.j...@gmail.com> wrote:
On Apr 23, 7:40 pm, aalfred <alfred.anzlo...@gmail.com> wrote:
> 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')
I think you won't need your new sugar if you just rewrite the
originals:
foo = bar if bar # case 1
foo ||= bar if bar # case 2
At Tue, 24 Apr 2007 19:40:06 +0900,
aalfred wrote in [ruby-talk:248941]:
> foo = bar if bar # case 1
> foo ||= bar if bar # case 2
>
> That's the simplest and cleanest, I think.
There is a subtelty in the assignment that is hard to see at the first
glance: you *never* assign nil to foo (but assign can false).
So your rewrite is not equivalent.
Ruby doesn't distinguish nil and false as boolean, so if ??=
were introduced it would not assign false.