Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntactic sugar for Safe Navigation operator(&.)

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?

like image 250
sbs Avatar asked Dec 25 '22 10:12

sbs


2 Answers

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:

  • Bug #11618: Safe call syntax with aref or aset is
  • Feature #11813: Extend safe navigation operator for [] and []= with syntax sugar

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).

like image 193
Jörg W Mittag Avatar answered Jan 12 '23 02:01

Jörg W Mittag


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

like image 42
crackedmind Avatar answered Jan 12 '23 03:01

crackedmind