Ruby参数末尾的&符是什么意思?

时间:2017-08-02 06:55:05

标签: ruby-on-rails ruby

以下是Ruby中命名参数的示例,但是&符号有什么作用?

def set_tools(foo:, bar:, baz:)
    @instance_variable = baz&.stuff

1 个答案:

答案 0 :(得分:6)

它被称为安全导航操作员。在ruby 2.3.0中引入

您可以在调用某个方法之前使用它来确保该值存在

例如:

a = nil

a.some_method # This will break

#=> NoMethodError: undefined method `some_method' for nil:NilClass

a&.some_method # This will not

#=> nil

您可以使用此运算符代替

a && a.some_method && a.some_method.some_other_method
# OR
a.try(:some_method).try(:some_other_method)

使用此运算符

a&.some_method&.some_other_method