I am working on a Ruby on Rails program currently and need a bit of help figuring out a method to take in a nested hash, extract the values, and concatenate those values together into a single String.
An example hash would be:
h={a:"da",b:{c:"test",e:{f:"bird"}},d:"duck"}
I would like the input to appear as such:
"datestbirdduck"
Would anyone be able to help with a metohod that can do this. I've had some trouble finding anything that works for a nested hash.
As your input (
h) is a hash that can contain hashes in its values, you can implement the method to extract the strings from the values using recursion:What it does is to receive the hash (
input) from which extract the values adding a guard clause - as the base case, which returns the argument the method was called with if it's a hash object, otherwise it flattens and map the object invoking the method itself. This way you extract every value from the initial method argument.Notice this extracts anything that's in the input that's not directly a hash, if you happen to have an object like this:
The result would be: