Nils and method chaining

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

    Starting from ruby v2.3.0 there is another way built into the language, the safe navigation operator (&.) You can write: a&.b&.c&.d and you will safely get nil if one of the calls in the chain returns nil. You can read more about it here: http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/

提交回复
热议问题