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?
You forgot to put a
.before thetry:since
[]is the name of the method when you do[@comment.id].