Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply deep_symbolize_keys! to array of hashes

deep_symbolize_keys! converts string keys to symbol keys. This works for hashes and all sub-hashes. However, I have a data like this:

arr = [
   {'name': 'pratha', 'email': '[email protected]', 'sub': { 'id': 1 } },
   {'name': 'john', 'email': '[email protected]', 'sub': { 'id': 2 } }
]
arr.deep_symbolize_keys! # this is not working for array of hashes.

In this case, hashes are in an array. So how can i symbolize all at once?

Using Ruby 2.6.3

I also read somewhere that this is deprecated (probably on one of the Rails forum). Is that true? If so, what is the best way to convert keys to symbols in my case?

Currently using this:

def process(emails)
  blacklist = ["a", "john", "c"]
  e = emails.map do |hash| 
    blacklist.include?(hash['name']) ? nil : hash.deep_symbolize_keys!
  end

  e
end
like image 905
Dennis Avatar asked Sep 17 '25 16:09

Dennis


1 Answers

Do you need a copy or an in-place transformation? In-place you can use arr.each(&:deep_symbolize_keys!). For a copy you should use arr.map(&:deep_symbolize_keys). Remember that map does not mutate but returns a new array.

like image 89
Artur Martsinkovskyi Avatar answered Sep 19 '25 06:09

Artur Martsinkovskyi