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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With