know thy collection helpers
Are you tired of seeing blog posts that takes a familiar chunk of code and turns it into a one liner? Neither am I, how could you possibly be. This weeks installment comes from a situation where i have task lists and tasks in the usual parent-child relationship. For reasons not explained here I have a list of tasks that reference their own copy of their task list parent. So now I am wanting to collect a unique set of the task lists.
Here is what I came up with
def self.collect_unique_parents(tasks)
task_lists = []
tasks.each do |task|
task_list = task.task_list
task_lists << task_list unless task_lists.include?(task_list)
end
task_lists
end
task_lists = collect_unique_parents(tasks)
But I decided to consult the available collection helpers and realized that group_by would be a good fit for this case. Also symbol-to-proc is thrown in for good measure.
task_lists = tasks.group_by(& :task_list).keys
However, beware that this will mess up any sort ordering because the group_by is hashing the results and I'm just pulling them back out with #keys.
