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 []?
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:
- Error # 11618: safe call syntax using isf or aset
- Feature # 11813: Extending a Safe Navigation Operator for
[]and[]=Using Syntax Sugar
I am not going to add safe navigation for isf and aset. Perhaps you can use
a.?[](x)(call operator method).