Created
September 27, 2011 02:42
-
-
Save fabrizioc1/1244183 to your computer and use it in GitHub Desktop.
Pivot child to parent relationship
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
@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 |
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
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