title: Converting nested hash keys from CamelCase to snake_case in Ruby
body: <p>I'm trying to build an API wrapper gem, and having issues with converting hash keys to a more Rubyish format from the JSON the API returns.</p>
  
  <p>The JSON contains multiple layers of nesting, both Hashes and Arrays. What I want to do is to recursively convert all keys to snake_case for easier use.</p>
  
  <p>Here's what I've got so far:</p>
  
  <pre><code>def convert_hash_keys(value)
    return value if (not value.is_a?(Array) and not value.is_a?(Hash))
    result = value.inject({}) do |new, (key, value)|
      new[to_snake_case(key.to_s).to_sym] = convert_hash_keys(value)
      new
    end
    result
  end
  </code></pre>
  
  <p>The above calls this method to convert strings to snake_case:</p>
  
  <pre><code>def to_snake_case(string)
    string.gsub(/::/, '/').
    gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
    gsub(/([a-z\d])([A-Z])/,'\1_\2').
    tr("-", "_").
    downcase
  end
  </code></pre>
  
  <p>Ideally, the result would be similar to the following:</p>
  
  <pre><code>hash = {:HashKey =&gt; {:NestedHashKey =&gt; [{:Key =&gt; "value"}]}}
  
  convert_hash_keys(hash)
  # =&gt; {:hash_key =&gt; {:nested_hash_key =&gt; [{:key =&gt; "value"}]}}
  </code></pre>
  
  <p>I'm getting the recursion wrong, and every version of this sort of solution I've tried either doesn't convert symbols beyond the first level, or goes overboard and tries to convert the entire hash, including values.</p>
  
  <p>Trying to solve all this in a helper class, rather than modifying the actual Hash and String functions, if possible.</p>
  
  <p>Thank you in advance.</p>