How to elegantly symbolize_keys for a 'nested' hash

How to elegantly symbolize_keys for a 'nested' hash

Consider the following code:

Consider the following code:

  hash1 = {"one" => 1, "two" => 2, "three" => 3}
  hash2 = hash1.reduce({}){ |h, (k,v)| h.merge(k => hash1) }
  hash3 = hash2.reduce({}){ |h, (k,v)| h.merge(k => hash2) }
  hash4 = hash3.reduce({}){ |h, (k,v)| h.merge(k => hash3) }

hash4 is a 'nested' hash i.e. a hash with string keys and similarly 'nested' hash values.

The 'symbolize_keys' method for Hash in Rails lets us easily convert the string keys to symbols. But I'm looking for an elegant way to convert all keys (primary keys plus keys of all hashes within hash4) to symbols.

The point is to save myself from my (imo) ugly solution:

  class Hash
    def symbolize_keys_and_hash_values
      symbolize_keys.reduce({}) do |h, (k,v)|
        new_val = v.is_a?(Hash) ? v.symbolize_keys_and_hash_values : v
        h.merge({k => new_val})

hash4.symbolize_keys_and_hash_values #=> desired result

FYI: Setup is Rails 3.2.17 and Ruby 2.1.1


Answer is hash4.deep_symbolize_keys for Rails <= 5.0

Answer is JSON.parse(JSON[hash4], symbolize_names: true) for Rails > 5

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Ruby on Rails vs PHP

Understanding the pros and cons of Ruby on Rails versus PHP is important when deciding how to create your business-critical applications.