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.
This has been added to Ruby 2.3.
The syntax is
obj1&.meth1&.meth2
.In a rails app there is
Object#try
So you can do
or with a block (as said on comments bellow)
UPDATE
In ruby 2.3 there is operator for this:
Which is the same as
obj && obj.value && obj.value.foo
Ruby 2.3 will have support for the safe navigation operator:
https://www.ruby-lang.org/en/news/2015/11/11/ruby-2-3-0-preview1-released/
try
was the only standard way to do this before Ruby 2.3. With Ruby 2.3 you can do:Also, if you have a hash structure, you can use the
_.
operator with Hashie: