4
str = "Hello World!"
str.[] /Hello/    # => "Hello"
str[/Hello/]      # => "Hello", syntactic suger version

str = nil
str&.[] /Hello/   # => nil
str&.[/Hello/]    # => SyntaxError: unexpected '[', expecting '('
str[/Hello/]      # => NoMethodError: undefined method `[]' for nil:NilClass

How can the Safe Navigation operator(&.) be used on syntactic sugar for []method?

sbs
  • 4,102
  • 5
  • 40
  • 54

2 Answers2

7

How can the Safe Navigation operator(&.) be used on syntactic sugar for []method?

It can't. Matz doesn't want it to.

This feature was requested and rejected twice already:

Matz says:

I am not going to add safe navigation for aref and aset. Maybe you can use a.?[](x) (method call of an operator).

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
3

Answer is short - you can't. Becase "method name is syntactically required" from Ruby 2.3 NEWS

crackedmind
  • 918
  • 6
  • 14