M
Max Williams
I was looking for a method to split an array into smaller arrays based
on some property of the members (set with a code block). I came up with
the following and wanted to know what you guys think about a) whether
it's sensible b) whether it's been done already:
class Array
def group_by
result_array = []
self.each do |element|
key = yield element
if (found = result_array.assoc(key))
found[1] << element
else
result_array << [key, [element]]
end
end
return result_array.collect{|a| a[1]}
end
end
=> ["apple", "banana", "pear", "plum", "nectarine", "orange", "melon"]
#group by length of name=> [["apple", "melon"], ["banana", "orange"], ["pear", "plum"],
["nectarine"]]
#group by whether it has an e=> [["apple", "pear", "nectarine", "orange", "melon"], ["banana",
"plum"]]
One thing i haven't done is make it sort: since the grouping key is just
an object and most objects aren't sortable. I could get round this but
not without slowing it down and the user can always sort the results by
comparing the first member of each subarray.
I'm just after some feedback really. I'm guessing i just couldn't find
the good implementation of it
on some property of the members (set with a code block). I came up with
the following and wanted to know what you guys think about a) whether
it's sensible b) whether it's been done already:
class Array
def group_by
result_array = []
self.each do |element|
key = yield element
if (found = result_array.assoc(key))
found[1] << element
else
result_array << [key, [element]]
end
end
return result_array.collect{|a| a[1]}
end
end
=> ["apple", "banana", "pear", "plum", "nectarine", "orange", "melon"]
#group by length of name=> [["apple", "melon"], ["banana", "orange"], ["pear", "plum"],
["nectarine"]]
#group by whether it has an e=> [["apple", "pear", "nectarine", "orange", "melon"], ["banana",
"plum"]]
One thing i haven't done is make it sort: since the grouping key is just
an object and most objects aren't sortable. I could get round this but
not without slowing it down and the user can always sort the results by
comparing the first member of each subarray.
I'm just after some feedback really. I'm guessing i just couldn't find
the good implementation of it