Created
July 16, 2015 15:52
-
-
Save coreymartella/99a8b14c20d7bd26895f to your computer and use it in GitHub Desktop.
array#to_tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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