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

后端 未结 4 592
傲寒
傲寒 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

    0 讨论(0)
  • 2020-12-17 09:41

    Ruby 2.3 will have support for the safe navigation operator:

    obj1&.obj2&.value
    

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

    0 讨论(0)
  • 2020-12-17 09:44

    try was the only standard way to do this before Ruby 2.3. With Ruby 2.3 you can do:

    if obj1&.obj2&.value
    
    end
    

    Also, if you have a hash structure, you can use the _. operator with 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
    
    0 讨论(0)
  • 2020-12-17 09:48

    This has been added to Ruby 2.3.

    The syntax is obj1&.meth1&.meth2.

    0 讨论(0)
提交回复
热议问题