Hash join: Difference between revisions

added ruby
(added ruby)
Line 280:
((28, 'Alan'), ('Alan', 'Zombies'))
((28, 'Glory'), ('Glory', 'Buffy'))
</pre>
 
=={{header|Ruby}}==
<lang ruby>def hashJoin(table1, table2)
# hash phase
h = table1.group_by {|s| s[1]}
# join phase
table2.collect {|r|
k = r[0]
h[k].collect {|s| [s, r]}
}.flatten(1)
end
 
table1 = [[27, "Jonah"],
[18, "Alan"],
[28, "Glory"],
[18, "Popeye"],
[28, "Alan"]]
table2 = [["Jonah", "Whales"],
["Jonah", "Spiders"],
["Alan", "Ghosts"],
["Alan", "Zombies"],
["Glory", "Buffy"]]
 
hashJoin(table1, table2).each { |row| p row }</lang>
{{out}}
<pre>
[[27, "Jonah"], ["Jonah", "Whales"]]
[[27, "Jonah"], ["Jonah", "Spiders"]]
[[18, "Alan"], ["Alan", "Ghosts"]]
[[28, "Alan"], ["Alan", "Ghosts"]]
[[18, "Alan"], ["Alan", "Zombies"]]
[[28, "Alan"], ["Alan", "Zombies"]]
[[28, "Glory"], ["Glory", "Buffy"]]
</pre>
 
Anonymous user