title: Ruby - Access multidimensional hash and avoid access nil object
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/5393974/ruby-nils-in-an-if-statement">Ruby: Nils in an IF statement</a><br>
    <a href="https://stackoverflow.com/questions/5429790/is-there-a-clean-way-to-avoid-calling-a-method-on-nil-in-a-nested-params-hash">Is there a clean way to avoid calling a method on nil in a nested params hash?</a>  </p>
  </blockquote>
  
  
  
  <p>Let's say I try to access a hash like this:</p>
  
  <pre><code>my_hash['key1']['key2']['key3']
  </code></pre>
  
  <p>This is nice if key1, key2 and key3 exist in the hash(es), but what if, for example key1 doesn't exist?</p>
  
  <p>Then I would get <code>NoMethodError: undefined method [] for nil:NilClass</code>. And nobody likes that.</p>
  
  <p>So far I deal with this doing a conditional like:</p>
  
  <p><code>if my_hash['key1'] &amp;&amp; my_hash['key1']['key2']</code> ...</p>
  
  <p>Is this appropriate, is there any other Rubiest way of doing so?</p>