Nils and method chaining

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

    To use a safe_nils similar to that you wrote:

    def safe_nils &blk
      return blk.call
    rescue NoMethodError
      return nil
    end
    
    safe_nils { a.b.c("d").e }
    

提交回复
热议问题