“[]”在以下上下文中代表什么?
有人可以解释以下之间的区别吗:
&.[](:key)
.try(:[],:key)
.try(:key)
特别是第一个和第二个中的“[]”代表什么?
回答
.[]是对象上的方法Hash。
x.[](:key)[]用:key参数调用方法,等价于x[:key]
&是安全导航运营商。x&.[](:key)将返回nilif xis nilwhilex.[](:key)会导致错误。
x = {key: 123}
x[:key]
# => 123
x.[](:key)
# => 123
x = nil
x.[](:key)
# NoMethodError: undefined method `[]' for nil:NilClass
x&.[](:key)
# => nil
就差异而言,我不相信第一个和第二个之间有任何区别,但是x.try(:key)会尝试调用一个key方法x并且会出错,因为它不存在。
x.try(:[], :key)调用.[]方法 with:key作为参数,相当于我们上面看到的。与安全导航操作符一样,try返回nilif xis nil。
- Depending on the Rails version, [`x.try(:m)`](https://api.rubyonrails.org/classes/Object.html#method-i-try) will give you `nil` if `x.nil?` or `!x.respond_to?(:m)` where as [`x.try!(:m)`](https://api.rubyonrails.org/classes/Object.html#method-i-try-21)` will give you `nil` if `x.nil?` and `NoMethodError` if `!x.nil? && !x.respond_to?(:m)`. So `try` does a little more than `&.` and `try!` is pretty much `&.`.