相当于 Rails 的安全导航尝试哈希 [英] Safe navigation equivalent to Rails try for hashes
本文介绍了相当于 Rails 的安全导航尝试哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Rails 中,您可以执行 hash.try(:[], :key)
如果 hash
可能是 nil
,这会有所帮助.是否有使用新的 Ruby 2.3 安全导航运算符 &.
和 []
的等效版本?
In Rails, you can do hash.try(:[], :key)
which helps if hash
is potentially nil
.
Is there an equivalent version for using the new Ruby 2.3 safe navigation operator &.
with []
?
推荐答案
&.
不等同于 Rails 的 try
,但你可以使用 &.
用于哈希.就用吧,没什么特别的.
&.
is not equivalent to Rails' try
, but you can use &.
for hashes. Just use it, nothing special.
hash[:key1]&.[](:key2)&.[](:key3)
虽然我不会那样做.
这篇关于相当于 Rails 的安全导航尝试哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文