Is there an equivalent null prevention on chained attributes of groovy in ruby?

后端 未结 3 1262
礼貌的吻别
礼貌的吻别 2020-12-11 16:41

Groovy:

if there`s my_object -> access \'name\' and capitalize

my_object?.name?.capitalize()

What is the equivalent for ruby to avo

3条回答
  •  独厮守ぢ
    2020-12-11 17:09

    Assuming you mean you want to avoid a nil error if my_object is nil. Try :

    my_object?.name?.capitalize() unless my_object.nil?
    

    Ruby will do the nil check first and only then try to access the attribute if my_object isn't a null.

    Dave

提交回复
热议问题