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 sugar 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.