Nils and method chaining

后端 未结 9 2499
忘了有多久
忘了有多久 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条回答
  •  Happy的楠姐
    2021-02-14 19:42

    One approach is to use inline assignment to local variables:

    a && (ab = a.b) && (abcd = ab.c("d")) && abcd.e
    

    For as long a chain as you've got here it isn't very elegant, but for a shorter chain it can be useful:

    def date_updated(entry)
      (updated = entry.updated) && updated.content
    end
    

提交回复
热议问题