Just thought I''d share a function which has been really useful to me,
for 2
reasons
1) It could easily help someone else
2) People might be able to make it work better or point out where it''s
not
optimal
class Array
# Groups elements of an array based on a user-defined condition
#
# Each element from this array is passed to the block, and the returned value
# determines the key under which it will be stored in the output hash
#
# If no block is given then the array indices will be used as the hash keys
def group_by
hsh = {}
self.dup.each_with_index do |element, i|
if block_given?
key = yield element
else
key = i
end
hsh[key] ||= []
hsh[key] << element
end
hsh
end
end
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---