简体   繁体   English

Ruby是否具有nil值的安全导航操作符的语法,比如Groovy?

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

In Groovy, there is a nice syntax for working with null values. 在Groovy中,有一个很好的语法来处理null值。

For example, I can do an if statement: 例如,我可以做一个if语句:

if (obj1?.obj2?.value) {

}

This will not throw a NullPointerException even if obj1 is null (it will evaluate to false). 即使obj1为null(它将评估为false),也不会抛出NullPointerException。

This is something that's very convenient, so wondering if there is a Ruby equivalent I missed. 这是非常方便的,所以想知道我是否错过了Ruby等价物。

In a rails app there is Object#try 在rails应用程序中有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 UPDATE

In ruby 2.3 there is operator for this: 在ruby 2.3中有运算符:

obj&.value&.foo

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

This has been added to Ruby 2.3. 这已被添加到Ruby 2.3中。

The syntax is obj1&.meth1&.meth2 . 语法是obj1&.meth1&.meth2

Ruby 2.3 will have support for the safe navigation operator: Ruby 2.3将支持安全导航操作员:

obj1&.obj2&.value

https://www.ruby-lang.org/en/news/2015/11/11/ruby-2-3-0-preview1-released/ https://www.ruby-lang.org/en/news/2015/11/11/ruby-2-3-0-preview1-released/

try was the only standard way to do this before Ruby 2.3. try是在Ruby 2.3之前执行此操作的唯一标准方法。 With Ruby 2.3 you can do: 使用Ruby 2.3,您可以:

if obj1&.obj2&.value

end

Also, if you have a hash structure, you can use the _. 此外,如果您有哈希结构,则可以使用_. operator with Hashie : Hashie的运营商:

require 'hashie'
myhash = Hashie::Mash.new({foo: {bar: "blah" }})

myhash.foo.bar
=> "blah"    

myhash.foo?
=> true

# use "underscore dot" for multi-level testing
myhash.foo_.bar?
=> true
myhash.foo_.huh_.what?
=> false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM