Extract values from Ruby data hash and concatenate values into single continuous String

219 Views Asked by At

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.

1

There are 1 best solutions below

5
Sebastián Palma On BEST ANSWER

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:

input = {a: "da", b: {c:"test", e: {f: "bird"}}, d:"duck"}

def extract_values_from_hash(input)
  return input unless input.is_a?(Hash)

  input.flat_map { |_, v| extract_values_from_hash(v) }
end

extract_values_from_hash(input).join
# datestbirdduck

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:

{a: "da", b: {c:"test", e: {f: "bird"}}, d:"duck", g: 1, h: [{i: "hola"}, {j: "chao"}]}

The result would be:

"datestbirdduck1{:i=>\"hola\"}{:j=>\"chao\"}"