title: Ruby (or Rails) type-safe "try"-equivalent
body: <p>I want to check values in a user-input hash (parameters passed to a Rails controller). I want to protect myself against bogus user input. Object#try protects me against missing input, but what about malformed input?</p>
  
  <p>The simple, unsafe case:</p>
  
  <pre><code>  if params[:credentials][:login] …
  </code></pre>
  
  <p>Obviously, if the user hasn't provided the :credentials value, then my attempt to get :login will fail … Nil doesn't have the method :[]. A very nice solution to this is Object#try:</p>
  
  <pre><code>  if params[:credentials].try(:[], :login) … 
  </code></pre>
  
  <p>But what if the issue is that the user provided malformed credentials? In particular, one of my users passed an array, rather than a hash. So I still get an exception,</p>
  
  <pre><code>TypeError: can't convert Symbol into Integer
  </code></pre>
  
  <p>Is there something rather like try(), that turns any bogosity into false/nil?</p>
  
  <p>The closest I could come is</p>
  
  <pre><code>  if begin params[:credentials][:login]; rescue; false; end … 
  </code></pre>
  
  <p>Which is a bit cluttered -- though, I grant, still more compact and yet more general than explicit paranoia:</p>
  
  <pre><code>  if (params.has_key? :credentials and params[:credentials].is_a? Hash and params[:credentials].has_key? :login) … 
  </code></pre>