I find that I’m often doing things of this sort in my Ruby code:
if person
if person.shirt
if person.shirt.sleeve
...
end
end
..which I do to avoid NoMethodErrors. I’m wondering if there’s any way that I can collapse this into one line, without the obvious
if person && person.shirt && person.shirt.sleeve
Basically, I want to make my code more compact.
Inside those ifs you want to do something with a sleeve, right?
Rails has a nice helper,
try. It returns value if everything goes well, andnilotherwise. So, in this example, ifperson.shirtor evenpersonitself is nil, try will return nil as well.For vanilla ruby you can use
andandgem which provides similar functionality.Since ruby 2.3, you can use safe navigation operator: