"Hello" str[/Hello/] # => "Hello", syntactic suger v...">

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 I use the safe navigation operator ( &.) for syntactic sugar for a method []?

+4
source share
2 answers

How can I use the safe navigation operator ( &.) for syntactic sugar for a method []?

He can not. Matz does not want this.

This function has been requested and has already been rejected twice:

Matz says :

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

+7

, . " " Ruby 2.3 NEWS

+3

Source: https://habr.com/ru/post/1622855/


All Articles