[#71931] [Ruby trunk - Feature #11786] [Open] [PATCH] micro-optimize case dispatch even harder — normalperson@...

Issue #11786 has been reported by Eric Wong.

9 messages 2015/12/08

[ruby-core:72165] [Ruby trunk - Bug #11816] Partial safe navigation operator

From: matt.larraz@...
Date: 2015-12-16 00:38:20 UTC
List: ruby-core #72165
Issue #11816 has been updated by Matt Larraz.


My na=C3=AFve understanding is that `foo&.bar` should be a shorthand for `f=
oo && foo.bar`, and therefore the `&.` operator should take the same level =
of precedence as the `&&` operator.

Marc-Andre Lafortune wrote:
>     x =3D nil
>     x&.foo.bar # =3D> nil
>     x&.foo[42] # =3D> nil
>     x&.foo[42] =3D 43 # =3D> nil
>     x&.foo * 42 # =3D> nil=20
>     x&.foo + 42 # =3D> nil
>     x&.foo << 42 # =3D> nil
>     x&.foo < 42 # =3D> nil
>     x&.foo =3D=3D 42 # =3D> false     ### This is where the precedence of=
 &. is higher
>     x&.foo || 42 # =3D> 42
>     x&.foo ? 1 : 2  # =3D> 2

If you substitute `x&.foo` for `x && x.foo` in the above, they all evaluate=
 the same except for one:

~~~
x && x.foo =3D=3D 42 # =3D> nil
~~~
This makes sense, since `=3D=3D` is a method and not an operator.

----------------------------------------
Bug #11816: Partial safe navigation operator
https://bugs.ruby-lang.org/issues/11816#change-55576

* Author: Marc-Andre Lafortune
* Status: Open
* Priority: Normal
* Assignee: Yukihiro Matsumoto
* ruby -v: preview 2
* Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN, 2.2: UNKNOWN
----------------------------------------
I'm extremely surprised (and disappointed) that, currently:

    x =3D nil
    x&.foo.bar # =3D> NoMethodError: undefined method `bar' for nil:NilClass

To make it safe, you have to write `x&.foo&.bar`. But if `foo` is never sup=
posed to return `nil`, then that code isn't "fail early" in case it actuall=
y does. `nil&.foo.bar` is more expressive, simpler and is perfect if you wa=
nt to an error if `foo` returned `nil`. To actually get what you want, you =
have to resort using the old form `x && x.foo.bar`...

In CoffeeScript, you can write `x()?.foo.bar` and it will work well, since =
it gets compiled to

    if ((_ref =3D x()) !=3D null) {
      _ref.foo.bar;
    }

All the discussion in #11537 focuses on `x&.foo&.bar`, so I have to ask:

Matz, what is your understanding of `x&.foo.bar`?

I feel the current implementation is not useful and should be changed to wh=
at I had in mind. I can't see any legitimate use of `x&.foo.bar` currently.




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

In This Thread

Prev Next