Nils and method chaining

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

提交回复
热议问题