Is there a .? operator in Ruby that checks if an object is nil before calling a method on it?
For instance if I have to code:
if person and person.neighbor and person.neighbor.house and person.neighbor.house.rooms
person.neighbor.house.rooms.each do |room|
blah
end
end
Is there a better way than having to do an if check on everything?
And please don't say "code in such a way that these objects cannot ever be nil", I am getting these things from an API call and can't control it.
As of Ruby 2.3.0, the &. "safe navigation" operator does exactly this. So instead of
person and person.neighbor and person.neighbor.house and person.neighbor.house.rooms
you can now just do
person&.neighbor&.house&.rooms.
http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/
Easiest thing to do is use the andand gem, although there are some other, pretty trivially-implemented options, like this, or this, or etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With