Created
October 6, 2015 16:20
-
-
Save anonymous/314cf192b884ff26ee01 to your computer and use it in GitHub Desktop.
How to recursively compress a hash, starting from the innermost values.
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
#!/usr/bin/env ruby | |
# encoding: utf-8 | |
hash_collector = {} | |
# Assign people | |
hash_collector["James"] = {} | |
hash_collector["John"] = {} | |
hash_collector["Bert"] = {} | |
hash_collector["Ernie"] = {} | |
# Assign roles | |
hash_collector["James"]["artist"] = [] | |
hash_collector["John"]["athlete"] = [] | |
hash_collector["John"]["dancer"] = [] | |
hash_collector["Bert"]["oenophile"] = [] | |
hash_collector["Ernie"]["oenophile"] = [] | |
# Assign gear | |
hash_collector["James"]["artist"].push "paintbrush" | |
hash_collector["John"]["athlete"].push "shoes" | |
hash_collector["John"]["dancer"].push "shoes" | |
hash_collector["Bert"]["oenophile"].push "red wine" | |
hash_collector["Bert"]["oenophile"].push "white wine" | |
hash_collector["Ernie"]["oenophile"].push "red wine" | |
hash_collector["Ernie"]["oenophile"].push "white wine" | |
hash_collector.keys.each do |key_person| | |
puts "+- #{key_person}" | |
hash_collector[key_person].keys.each do |key_profession| | |
puts "| +- #{key_profession}" | |
hash_collector[key_person][key_profession].each do |array_element| | |
puts "| | +- #{array_element}" | |
end | |
end | |
end | |
=begin | |
############## Real Output ############## | |
+- James | |
| +- artist | |
| | +- paintbrush | |
+- John | |
| +- athlete | |
| | +- shoes | |
| +- dancer | |
| | +- shoes | |
+- Bert | |
| +- oenophile | |
| | +- red wine | |
| | +- white wine | |
+- Ernie | |
| +- oenophile | |
| | +- red wine | |
| | +- white wine | |
############## Desired Output ############## | |
+- James | |
| +- artist | |
| | +- paintbrush | |
+- John | |
| +- athlete,dancer | |
| | +- shoes | |
+- Bert,Ernie | |
| +- oenophile | |
| | +- red wine | |
| | +- white wine | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment