Naming question

R

Robert Dober

Hi list

I actually just need the following method there is no doubt about it;)
but the name which sprang into mind naturally "partition_by"
has a serious shortcoming, it is not POLS in the sense that
Enumerable#partition returns an array and Enumerable#partition_by
returns a hash.

module Enumerable
def partition_by &blk
result = Hash.new {|h,k| h[k] = [] }
each do | element |
result[ element ] << blk.call element
end
result
end
end


Any ideas for a nice different name?
Does Facet implement the above maybe?

A remark for my fellow fans of inject, the same code with inject
somehow does not feel right, I do not like to use inject with this
pattern
inject(...){ |acc,ele|
...
acc
}

Thanx in advance
Robert
 
R

Robert Dober

Does Facet implement the above maybe?
Enumerable#cluster_by
great that would have been a nice name thanx Tom ;)
but I can live with your group_by :)
issue resolved

Actually I never thaught that Facets doc was so darn pretty good that
I could find it myself, should never have asked....

R.
 
P

Peña, Botp

From: Robert Dober [mailto:[email protected]]=20
# module Enumerable
# def partition_by &blk
# result =3D Hash.new {|h,k| h[k] =3D [] }
# each do | element |
# result[ element ] << blk.call element
# end
# result
# end
# end

i think this is #group_by in 1.8.7 and 1.9 ?

kind regards -botp
 
R

Robert Dober

module Enumerable
def group_by
result = Hash.new { |h, k| h[k] = Array.new }
self.each do |item|
group = yield(item)
result[group] << item
end
return result
end
end

This is the code of the post linked to above, as one can see it works,
not as mine above :)
but this natural way to write it is quite inefficient as the Facets
version shows. I have benchmarked them and to my surprise and that of
many others I guess the Facets implementation is almost twice as fast
- for many different keys at least

result = {}
each do | ele|
( result[ yield(ele) ] ||= [] ) << ele
end
result.

Does anybody have the faintest idea why Hash.new{|h,k| ... } is so inefficient?

BTW I am quite happy that #group_by is quasi a standard name for this.

Cheers
Robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top