Skip to content

Instantly share code, notes, and snippets.

@fabrizioc1
Created September 27, 2011 02:42
Show Gist options
  • Save fabrizioc1/1244183 to your computer and use it in GitHub Desktop.
Save fabrizioc1/1244183 to your computer and use it in GitHub Desktop.
Pivot child to parent relationship
@child_and_parent = {
:b=>:a,
:c=>:a,
:x=>:a,
:d=>:b,
:e=>:b,
:f=>:c,
:g=>:c,
:h=>:g,
:i=>:h
}
# 'Inject' is Ruby's REDUCE method
@parent_and_children=@child_and_parent.keys.inject({}) do |new_hash,key|
new_hash[@child_and_parent[key]] ||= []
new_hash[@child_and_parent[key]] << key
new_hash
# Using Ruby 1.9 you can collapse the 3 lines above to one line:
# new_hash.tap do |this_hash| (this_hash[@child_and_parent[key]] ||= []) << key; end
end
irb(main):021:0> load 'hierarchy.rb'
=> true
irb(main):022:0> @parent_and_children
=> {:a=>[:b, :c, :x], :b=>[:d, :e], :c=>[:f, :g], :g=>[:h], :h=>[:i]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment