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
安全导航运算符(&.
)如何用于[]
方法的语法糖?