Issue #11537 has been updated by Tom Reznick.


Hi,

I think we may have found some unexpected behavior with the `.?` operator.

If I call the following:
```
s = Struct.new(:x)
o = s.new()
o.x #=> nil
o.x.nil? #=> true
o.x.?nil? #=> nil
o.x.kind_of?(NilClass) #=> true
o.x.?kind_of?(NilClass) #=> nil
o.x.methods.include?(:nil?) #=> true
```

While it's arguably a bit peculiar to try to check that `nil` is `nil`, in a `nil`-safe way, `.?kind_of?(NilClass)` could reasonably return `true`.

Also this is clearly a bit of a contrived example, it does highlight some of the more unexpected behaviors of the `.?` operator.

Any chance of clarification?

All best!

Tom Reznick
Software Engineer
Continuity
@threznick

Nobuyoshi Nakada wrote:
> Applied in changeset r52214.
> 
> ----------
> Safe navigation operator
> 
> * compile.c (iseq_peephole_optimize): peephole optimization for
>   branchnil jumps.
> * compile.c (iseq_compile_each): generate save navigation operator
>   code.
> * insns.def (branchnil): new opcode to pop the tos and branch if
>   it is nil.
> * parse.y (NEW_QCALL, call_op, parser_yylex): parse token '.?'.
>   [Feature #11537]



----------------------------------------
Feature #11537: Introduce "Safe navigation operator"
https://bugs.ruby-lang.org/issues/11537#change-54530

* Author: Hiroshi SHIBATA
* Status: Closed
* Priority: Normal
* Assignee: Yukihiro Matsumoto
----------------------------------------
I sometimes write following code with rails application:

```ruby
u = User.find(id)
if u && u.profile && u.profile.thumbnails && u.profiles.thumbnails.large
  ...
```

or

```ruby
# Use ActiveSupport
if u.try!(:profile).try!(:thumbnails).try!(:large)
 ...
```
I hope to write shortly above code. Groovy has above operator named "Safe navigation operator" with "`?.`" syntax.
Ruby can't use "`?.`" operator.

Can we use "`.?`" syntax. like this:

```ruby
u = User.find(id)
u.?profile.?thumbnails.?large
```

Matz. How do you think about this?




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