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?
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:
[]
and []=
with syntax sugarMatz says:
I am not going to add safe navigation for aref and aset. Maybe you can use
a.?[](x)
(method call of an operator).
Answer is short - you can't. Becase "method name is syntactically required" from Ruby 2.3 NEWS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With