title: Method to get value from a hash from array of keys in Ruby
body: <p>I am trying to write a function which returns the value of a hash key, when provided with an array of keys (and 'nil' if the key doesn't exist).</p>
  
  <p>Consider the hash:</p>
  
  <pre><code>my_hash = { 
    font_size: 10, 
    font_family: "Arial", 
    boo: { 
      name: 'blah' 
    } 
  }
  </code></pre>
  
  <p>A stub of the method might be:</p>
  
  <pre><code>def get_value(hash, array_of_keys)
    ...
  end
  </code></pre>
  
  <p>The reason being that I can access different keys in the hash which may not actually exist. So for example, I want 'blah', normally I would call <code>my_hash[:boo][:name]</code> however it may not already exist or it may be very deep. What I would like to do is have my function, which I could call with <code>get_value(my_hash, [:boo, :name])</code> so that I can test that each key exists (so I don't get exceptions if any of them do not exist, and where it doesn't matter how 'deep' the value might be).</p>
  
  <p>In my case, its not feasible to check the existence of each value I require (I might need to test existence of 10 consecutive keys) I simply need a function that I can say which value I need and get the value if it exists, and nil if it doesn't (so an exception isn't thrown trying to retrieve it).</p>
  
  <p>I gave it a shot, trying to use a recursive function that 'pop's the first element in the array each time it loops but i couldn't workout how to return my value.</p>
  
  <pre><code>def get_value(val, arr)
    if arr.count &gt; 1
      arr.each do |a|
        get_value val[a], arr.pop
      end
    else
      val[a]
    end
  end
  
  
  get_value s, [:boo, :name]
  </code></pre>
  
  <p>This is my attempt (which doesn't work obviously) - can anyone help me solve this problem, or have an alternate solution that might be more elegant? A couple of points:</p>
  
  <ul>
  <li>The keys are not guaranteed to exist, and I'd like to return nil in
  those cases, and </li>
  <li>The hash could potentially be very deep so it needs to handle any hash and any number of keys in the array (which is why I thought recursion might be the answer, but now I'm not so sure).</li>
  </ul>