I’m working on a project where I need to associate newspaper articles with the page numbers they appear on in print.
My input data is just a bunch of pairs of article titles and page numbers. I came up with the following code to create a new Hash where the keys are page numbers and the values are arrays of the article titles:
a = ["A1", "title 1"]
b = ["A1", "title 2"]
c = ["A2", "title 3"]
hash = {}
articles = [a,b,c]
articles.each do |a|
if hash.has_key?(a[0])
hash[a[0]] << a[1]
else
hash.merge!({a[0] => [a[1]]})
end
end
The code works well enough, but I’m wondering if there is a cleaner way of doing this. I checked the Ruby docs and couldn’t find any built in methods, but I’d like SO’s input on this.
Since Michael Kohl has been reminding of
group_bylately:Works the same in 1.9.2 and 1.8.7.