arrays - Select all values by key from a nested hash -


i want values of each key not nested 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 please tell me doing wrong?

wanted output [1,2,3] [1]

in solution, inner list_to_array method call doesn't update current result array, wasn't being updated correctly. i've refactored more stuff make more readable , exclude nil values

lists = {'value'=>1, 'next'=>{'value'=>2, 'next'=>{'value'=>3, 'next'=>nil}}}  def list_to_array(h, results = [])   h.each_value |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] 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -