Extend safe navigation operator for  and = with syntax sugar
Now we have the safe navigation operator
&.. But this cannot be used with syntax sugar form of the methods
=, which are more frequent than their ordinary forms of method call. For example, when
a can be either an array or
nil, we can do:
a &.(3) a &.= 2, :foo
but we cannot do:
a &. a &. = :foo
It would be nice if we can extend the use of
&. to cover syntactic sugar as above.
Updated by nobu (Nobuyoshi Nakada) almost 4 years ago
Usaku NAKAMURA wrote:
IMO, we can write
&.only for replacement of
As you know,
ary.[idx]is not valid, then
ary&.[idx]should not be valid, too.
That is same as matz's opinion and the reason it was removed at r52430.
parse.y: revert lbracket * parse.y (lbracket): remove .? before aref. [Feature #11537] revert r52422 and r52424
I don't think this proposal will be accepted.
We'll need a better notation.
Updated by TimTheTinker (Roy Tinker) over 3 years ago
It seems to me that a "safe subscript operator" should simply add a
& between the receiver and the subscript operator (making
a safe would mean changing it to
a&), just like safe navigation adds a
& between the receiver and the method invocation operator (
& is also a method name and is defined for several corelib classes (bitwise AND for
Fixnum, set intersection for
Array, boolean AND for
TrueClass). So if variable
a above were an array,
a& would return the set intersection of
. It is true that
a&.(3) accomplishes the desired outcome, but this involves using the subscript operator as a method name -- which obscures semantic intent.
Is it possible to define a "safe subscript operator" with simple and unique syntax?