像Groovy一样,Ruby是否具有用于nil值的安全导航运算符的语法? [英] Does Ruby have syntax for safe navigation operator of nil values, like in Groovy?
本文介绍了像Groovy一样,Ruby是否具有用于nil值的安全导航运算符的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Groovy中,有一个很好的语法可以处理空值.
In Groovy, there is a nice syntax for working with null values.
例如,我可以执行一个if语句:
For example, I can do an if statement:
if (obj1?.obj2?.value) {
}
即使obj1为null,它也不会引发NullPointerException(它将评估为false).
This will not throw a NullPointerException even if obj1 is null (it will evaluate to false).
这是非常方便的事情,所以想知道我是否错过了与Ruby等价的东西.
This is something that's very convenient, so wondering if there is a Ruby equivalent I missed.
推荐答案
在Rails应用中,存在Object#try
In a rails app there is Object#try
所以你可以做
obj1.try(:obj2).try(:value)
或带有一个块(如下面的评论所述)
or with a block (as said on comments bellow)
obj.try {|obj| obj.value}
更新
在ruby 2.3中,有此操作符:
In ruby 2.3 there is operator for this:
obj&.value&.foo
与obj && obj.value && obj.value.foo
这篇关于像Groovy一样,Ruby是否具有用于nil值的安全导航运算符的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文