Nils and method chaining

后端 未结 9 2469
忘了有多久
忘了有多久 2021-02-14 19:21

I\'m just breaking into the ruby world and I could use a helping hand.

Suppose b is nil.

I\'d like the following code to return n

相关标签:
9条回答
  • 2021-02-14 19:50

    You can use the inline rescue:

    x = a.b.c("d").e rescue nil
    

    x will be nil if b is nil.

    Or, as someone commented in that link, you can use the andand gem (see docs):

    x = a.andand.b.andand.c("d").andand.e
    
    0 讨论(0)
  • 2021-02-14 19:50

    "try" is very clean, as lucapette said. More generally, you could also use a begin-rescue-end block too, depending on your situation.

    begin
      a.b.c("d").e
    rescue NoMethodError=>e
      return nil
    end
    
    0 讨论(0)
  • 2021-02-14 19:58

    I've made the may_nil gem for this. https://github.com/meesern/may_nil

    Like @Sony Santos's safe_nils answer it uses a block to wrap the method chain and rescues NoMethodError, but will check for nil (and so will properly raise an exception for other classes).

    require `may_nil`
    may_nil {a.b.c("d").e}   => nil (or the end result)
    may_nil {0.b.c("d").e}   => Exception: NoMethodError (b on Fixnum)
    

    Unlike andand or ike's maybe you don't need to pepper the method chain.

    a.andand.b.andand.c("d").andand.e
    ==>
    may_nil{ a.b.c("d").e }
    
    0 讨论(0)
提交回复
热议问题