Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby have syntax for safe navigation operator of nil values, like in Groovy?

Tags:

In Groovy, there is a nice syntax for working with null values.

For example, I can do an if statement:

if (obj1?.obj2?.value) {  } 

This will not throw a NullPointerException even if obj1 is null (it will evaluate to false).

This is something that's very convenient, so wondering if there is a Ruby equivalent I missed.

like image 293
Jean Barmash Avatar asked Jun 22 '12 20:06

Jean Barmash


2 Answers

In a rails app there is Object#try

So you can do

obj1.try(:obj2).try(:value) 

or with a block (as said on comments bellow)

obj.try {|obj| obj.value} 

UPDATE

In ruby 2.3 there is operator for this:

obj&.value&.foo 

Which is the same as obj && obj.value && obj.value.foo

like image 139
Ismael Avatar answered Oct 30 '22 09:10

Ismael


This has been added to Ruby 2.3.

The syntax is obj1&.meth1&.meth2.

like image 44
jeremywoertink Avatar answered Oct 30 '22 10:10

jeremywoertink