Nils and method chaining

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

    "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
    

提交回复
热议问题