M
Michael Neumann
Hi,
I propose the addition of Enumerable#group_by which is a generalization
of Enumerable#partition.
module Enumerable
def group_by(store=Hash.new)
self.each do |elem|
group = yield elem
(store[group] ||= []) << elem
end
store
end
end
For example:
%w(This is a list of words).group_by {|word| word.size}
would result in:
{5=>["words"], 1=>["a"], 2=>["is", "of"], 4=>["This", "list"]}
Is this useful enough to include into Ruby?
Regards,
Michael
I propose the addition of Enumerable#group_by which is a generalization
of Enumerable#partition.
module Enumerable
def group_by(store=Hash.new)
self.each do |elem|
group = yield elem
(store[group] ||= []) << elem
end
store
end
end
For example:
%w(This is a list of words).group_by {|word| word.size}
would result in:
{5=>["words"], 1=>["a"], 2=>["is", "of"], 4=>["This", "list"]}
Is this useful enough to include into Ruby?
Regards,
Michael