安全导航运算符 (&.) 的语法糖
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?
不能。 Matz 不想这样。
此功能已被请求并被拒绝两次:
- Bug #11618: Safe call syntax with aref or aset is
- Feature #11813: Extend safe navigation operator for
[]
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).
答案很简短 - 你不能。因为 "method name is syntactically required" 来自 Ruby 2.3 新闻
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?
不能。 Matz 不想这样。
此功能已被请求并被拒绝两次:
- Bug #11618: Safe call syntax with aref or aset is
- Feature #11813: Extend safe navigation operator for
[]
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).
答案很简短 - 你不能。因为 "method name is syntactically required" 来自 Ruby 2.3 新闻