Does Ruby have syntax for safe navigation operator of nil values, like in Groovy?

后端 未结 4 595
傲寒
傲寒 2020-12-17 09:19

In Groovy, there is a nice syntax for working with null values.

For example, I can do an if statement:

if (obj1?.obj2?.value) {

}
<
4条回答
  •  既然无缘
    2020-12-17 09:38

    In a rails app there is Object#try

    So you can do

    obj1.try(:obj2).try(:value)
    

    or with a block (as said on comments bellow)

    obj.try {|obj| obj.value}
    

    UPDATE

    In ruby 2.3 there is operator for this:

    obj&.value&.foo
    

    Which is the same as obj && obj.value && obj.value.foo

提交回复
热议问题