antimuon antimuon - 1 year ago 58
Ruby Question

Are there any sql-like joins for ruby?

I am playing around with some data in ruby and experimenting with creating nested hash structures...let's say I have two tables that I convert to table is team-offense, the other is passing-offense and I want to join both into one data structure on a key = team...


Carolina Panthers,team-offence,2015,1,16,500,5871,1060,5.5,19,9,357,300,501,3589,35,10,6.7,197,526,2282,19,4.3,136,103,887,24,42.9,9.6,125.65
Carolina Panthers,team-offense,2014,19,16,339,5547,1060,5.2,23,11,347,327,545,3511,23,12,6,199,473,2036,10,4.3,117,83,756,31,34.8,11.8,29.83
Carolina Panthers,team-offense,2013,18,16,366,5069,999,5.1,19,6,319,292,473,3043,24,13,5.9,169,483,2026,14,4.2,122,80,671,28,36.5,9.4,70.12


Carolina Panthers,team-passing,2015,24,16,300,501,59.9,3589,35,7,10,2,74,7.7,8.2,12.9,224.3,99.2,33,284,6.7,7.2,6.2,3,4,122.36
Carolina Panthers,team-passing,2014,19,16,327,545,60,3511,23,4.2,12,2.2,51,7,6.9,11.7,219.4,86.2,42,317,6,5.8,7.2,3,2,56.09
Carolina Panthers,team-passing,2013,29,16,292,473,61.7,3043,24,5.1,13,2.7,79,7.1,6.9,11.6,190.2,88.8,43,336,5.9,5.7,8.3,4,4,54.85

I can create the separate hash 'tables'

{"Carolina Panthers" => [ {team-offense...}, {...}, {...} ] }
{"Carolina Panthers" => [ {team-passing...}, {...}, {...} ] }

Is there a way to create a join on key = team where my data structure would be two sets of hash 'tables', e.g.,...

{"Carolina Panthers" => [ {team-offense...}, {...}, {...} ],
[ {team-passing...}, {...}, {...} ] }

I know this may not be a most intuitive way to do things but I am trying to do some 'interesting' data structures with the data.

Answer Source
>> hash1 = {"Carolina Panthers" => ['team offense'] }
>> hash2 = {"Carolina Panthers" => ['team passing'] }
>> hash3 = { |team_name| [team_name, [hash1[team_name], hash2[team_name]]] }.to_h
=> {"Carolina Panthers"=>[["team offense"], ["team passing"]]}

That said, you will be greatly aided by creating a custom class and using objects with attributes to store the data. This kind of complex data structure will give you headaches. Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download