This question already has an answer here:
In Rails we can do the following in case a value doesn't exist to avoid an error:
@myvar = @comment.try(:body)
What is the equivalent when I'm digging deep into a hash and don't want to get an error?
@myvar = session[:comments][@comment.id]["temp_value"]
# [:comments] may or may not exist here
In the above case, session[:comments]try[@comment.id]
doesn't work. What would?
The proper use of try with a hash is
@sesion.try(:[], :comments)
.When you do this:
You're just chaining a bunch of calls to a "[]" method, an the error occurs if myhash[:one] returns nil, because nil doesn't have a [] method. So, one simple and rather hacky way is to add a [] method to Niclass, which returns nil: i would set this up in a rails app as follows:
Add the method:
Require the file:
Now you can call nested hashes without fear: i'm demonstrating in the console here:
The announcement of Ruby 2.3.0-preview1 includes an introduction of Safe navigation operator.
This means as of 2.3 below code
can be rewritten to
However, one should be careful that
&
is not a drop in replacement of#try
. Take a look at this example:It is also including a similar sort of way:
Array#dig
andHash#dig
. So now thiscan be rewritten to
Again,
#dig
is not replicating#try
's behaviour. So be careful with returning values. Ifparams[:country]
returns, for example, an Integer,TypeError: Integer does not have #dig method
will be raised.Andrew's answer didn't work for me when I tried this again recently. Maybe something has changed?
The
'[]'
is in quotes instead of a symbol:[]
From Ruby 2.0, you can do:
From Ruby 2.3, you can do:
You forgot to put a
.
before thetry
:since
[]
is the name of the method when you do[@comment.id]
.