Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.? (existence) operator in ruby?

Tags:

null

ruby

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.

like image 425
Razor Storm Avatar asked Feb 20 '26 22:02

Razor Storm


2 Answers

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/

like image 136
Milo P Avatar answered Feb 22 '26 17:02

Milo P


Easiest thing to do is use the andand gem, although there are some other, pretty trivially-implemented options, like this, or this, or etc.

like image 33
Dave Newton Avatar answered Feb 22 '26 17:02

Dave Newton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!