Using try method to check existence of key in hash
3 November, 2013
Parameter is a hash, frequently used to transfer data. Sometimes it nests as the following structure:
:user => {:name => "Ryan", :sex => "male", :age => "28"}
To access ‘:name’ in your controller, you probably write code like this:
def name
params[:user][:name]
end
Wait! Something is wrong. Rails will raise undefined method[:name] for nil
error when param[:user] doesn’t exit
Sadly, you have to clutter your code to make it work.
def name
params[:user] ? params[:user][:name] : nil
end
Actually, you have another choice - try method. Code can also be writen as
def name
params[:user].try(:[], :name)
end
Now it works perfectly and clean.
Look up .try method of Rails.