Nils and method chaining

后端 未结 9 2436
忘了有多久
忘了有多久 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: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 }
    

提交回复
热议问题