Issue #11813 has been updated by Roy Tinker.


It seems to me that a "safe subscript operator" should simply add a `&` between the receiver and the subscript operator (making `a[3]` safe would mean changing it to `a&[3]`), just like safe navigation adds a `&` between the receiver and the method invocation operator (`a.foo` => `a&.foo`).

Unfortunately, `&` is also a method name and is defined for several corelib classes (bitwise AND for Fixnum, set intersection for Array, boolean AND for FalseClass/NilClass/TrueClass). So if variable `a` above were an array, `a&[3]` would return the set intersection of `a` and `[3]`. 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 and appears like a hack.

Is it possible to define a "safe subscript operator" with simple and unique syntax?

----------------------------------------
Feature #11813: Extend safe navigation operator for [] and []= with syntax sugar
https://bugs.ruby-lang.org/issues/11813#change-59627

* Author: Tsuyoshi Sawada
* Status: Open
* Priority: Normal
* Assignee: Yukihiro Matsumoto
----------------------------------------
Now we have the safe navigation operator `&.`. But this cannot be used with syntax sugar form of the methods `[]` and `[]=`, 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 &.[3]
    a &.[2] = :foo

It would be nice if we can extend the use of `&.` to cover syntactic sugar as above.



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>