Project

General

Profile

Actions

Feature #11816

open

Partial safe navigation operator

Added by marcandre (Marc-Andre Lafortune) over 8 years ago. Updated about 4 years ago.

Status:
Assigned
Target version:
-
[ruby-core:72117]

Description

I'm extremely surprised (and disappointed) that, currently:

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

To make it safe, you have to write x&.foo&.bar. But if foo is never supposed to return nil, then that code isn't "fail early" in case it actually does. nil&.foo.bar is more expressive, simpler and is perfect if you want 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 = x()) != 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 what I had in mind. I can't see any legitimate use of x&.foo.bar currently.


Related issues 1 (0 open1 closed)

Precedes Ruby master - Bug #12296: [Backport] fix dangling linkClosedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0