From: Ryan Leavengood Date: 2005-06-27T02:40:12+09:00 Subject: Re: grouping/sorting [newbie question] bdarcus@gmail.com wrote: > Thanks Ryan. Certainly less verbose than xslt! Generally so. Here is an article by Martin Fowler about his switch from XSLT to Ruby for processing XML: http://www.martinfowler.com/bliki/MovingAwayFromXslt.html > So when you;'re using inject there, you're just creating a hash whose > key is the title? Correct. You give inject the initial value, which it injects into the block along with each value in the array. So we start with an empty hash and use the film titles as keys. The return value from the block is used to re-inject into the block (that is why I have the grouped hash at the bottom of the block.) > What is the "||=[]" bit doing? That is a bit of a Ruby idiom (that comes from Perl I think.) It is equivalent to var = var || []. If var is initially nil, it becomes a new array, and whenever the above code is called again, var is just re-assigned to itself. It just makes the code shorter. The verbose version from the code I sent is this: grouped_comments = films.inject({}) do |grouped, film| if grouped[film['title']].nil? grouped[film['title']] = [] end grouped[film['title']] << film['comments'] grouped end As you can see there is a lot of repetition, so it is a good idea to become familiar with this idiom. Ryan