Hash#transform_keys! is available when we want to symbolize hash keys.
But in some/many cases (for example, receiver hash object is nested configuration tree loaded from any files), hash object are
nested object, which has hashes or arrays of hashes as values.
It's super useful if we can transform keys of such nested values.
My proposal is Hash#transform_keys!(recursive: true, &:to_sym). Pseudo code is:
deftransform_keys!(recursive: false,&block)# do original transform_keys! herevalues.eachdo|v|ifv.respond_to?(:each)v.each{|i|i.transform_keys!(recursive: true,&block)ifi.respond_to?(:transform_keys!)}elsev.respond_to?(:transform_keys!)v.transform_keys!(recursive: true,&block)endendifrecursiveend
The most major usage example is: config = MyAwesomeFormat.load(file); config.transform_keys!(recursive: true, &:to_sym).
Why prefer each over transform_keys!?
And probably you wanted to write elsif.
Your points are correct. The ideal pseudo code is here:
deftransform_keys!(recursive: false,&block)# do original transform_keys! herevalues.eachdo|v|ifv.respond_to?(:transform_keys!)v.transform_keys!(recursive: true,&block)elsifv.respond_to?(:each)v.each{|i|i.transform_keys!(recursive: true,&block)ifi.respond_to?(:transform_keys!)}endendifrecursiveend
I don't think this proposal is a good idea for following reasons:
transform_keys method to modify value part of Hash
recursive option to change the behavior this much
it is much harder to implement transform_keys(recursive:true) (without bang)
I understand the intention behind the proposal. Probably you want to process JSON-like Array-Hash structures. I feel the recent demand to handle those data structures in Ruby. So we might need to add some utility methods in Ruby. I am not sure how yet. Maybe by adding methods to JSON module, or adding them both Array and Hash (like dig).