Skip to content

Instantly share code, notes, and snippets.

@coreymartella
Created July 16, 2015 15:52
Show Gist options
  • Save coreymartella/99a8b14c20d7bd26895f to your computer and use it in GitHub Desktop.
Save coreymartella/99a8b14c20d7bd26895f to your computer and use it in GitHub Desktop.
array#to_tree
class Array
def to_tree(*key_methods,&block)
reduce({}) do |tree,e|
key_path = block_given? ? yield(e) : key_methods.map{|m| e.instance_eval(m.to_s)}
sub_tree = tree
key_path.each_with_index do |k,i|
if i == key_path.size - 1
(sub_tree[k] ||= []) << e
elsif
sub_tree = (sub_tree[k] ||= {})
end
end
tree
end
end
end
#For example: Person.all.to_tree(:department, :job_title)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment