Equivalent of .try() for a hash to avoid "undefined method" errors on nil?

sscirrus picture sscirrus · Jun 3, 2011 · Viewed 80.4k times · Source

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?

Answer

Andrew Grimm picture Andrew Grimm · Jun 3, 2011

You forgot to put a . before the try:

@myvar = session[:comments].try(:[], @comment.id)

since [] is the name of the method when you do [@comment.id].