Using “try” with a hash to check existence of a key
The
trymethod is awesome. Check the documentation.
It is usually used to call a method on an object if it exists, or returnnilif it doesn’t.But sometimes, it is not used with hashes, but this also works perfectly:
params[:search] ? params[:search][:name] : nil # Can also be written as... params[:search].try(:[],:name)Clean!
This tip was submitted by Miguel Camba.
(Source: rubyquicktips)