This was a definite huh / aha moment - finding the idiomatic Ruby way to solve a typical problem, in this case, taking an array of objects, and grouping them in a hash so that each element in the hash was all of the objects belonging to a particular user.
You could parse out some unique value from your user object (which was the brain-damaged PHP way I had been thinking of this problem) and use that has a hash key:
#ugly
slug = (post.user.name +" "+post.user.id.to_s).to_sym
posts_by_user[slug] << post
When it turns out that you can use objects themselves as hash keys in Ruby, and then use the Hash.keys method to grab those objects back when you need them.
So if you had a Post, which belonged to User, and you wanted to get them all and group them by user (assuming that your ORM or whatever won't do it for you in this instance):
posts = Post.all
posts_by_user = Hash.new {|h,k| h[k]=[]}
posts.each do |post|
#if there is no entry for this user, create one with an empty array
posts_by_user[post.user] ||= []
#shovel the post on to the group for that user
posts_by_user[post.user] << post
end
Iterate through them like this -
posts_by_user.keys.each do |user|
#the user object
p user.inspect
#referencing the hash with the user object as key
posts_by_user[user].each do |post|
#each post belonging to that user
p post.inspect
end
end
No comments:
Post a Comment