user3173816 user3173816 - 5 months ago 13
Ruby Question

Select all values by key from a nested hash

I want to get the values of each key which is not nested into an array.

lists = {'value'=>1, 'next'=>{'value'=>2, 'next'=>{'value'=>3, 'next'=>nil}}}

def list_to_array(h)
result = []
h.each_value {|value|
value.is_a?(Hash) ? list_to_array(value) :
result << value
}
result
end

p list_to_array(lists)


Can you please tell me what I am doing wrong?

wanted output [1,2,3] but I get [1]

Answer

In your solution, the inner list_to_array method call doesn't update the current result array, so it wasn't being updated correctly. I've refactored some more stuff to make it more readable and to exclude nil values

lists = {'value'=>1, 'next'=>{'value'=>2, 'next'=>{'value'=>3, 'next'=>nil}}}

def list_to_array(h, results = [])
  h.each_value do |value|
    if value.is_a?(Hash)
      list_to_array(value, results)
    else
      results << value unless value.nil?
    end
  end

  results
end

p list_to_array(lists)

=> [1, 2, 3]