2011-03-30 9 views
5

Después de jugar mucho en la consola, se me ocurrió este método para agrupar objetos activos como monigotes (Mongoid) por el día en que ocurrieron. No estoy seguro de que esta sea la mejor manera de lograr esto, pero funciona. ¿Alguien tiene una mejor sugerencia, o es esta una buena manera de hacerlo?Agrupando Mongoid Objects por día

#events is an array of activerecord-like objects that include a time attribute 
events.map{ |event| 
    # convert events array into an array of hashes with the day of the month and the event 
    { :number => event.time.day, :event => event } 
}.reduce({}){ |memo,day| 
    # convert this into a hash with arrays of events keyed by their day or occurrance 
    (memo[day[:number]] ||= []) << day[:event] 
    memo 
} 

=> { 
     29 => [e1, e2], 
     28 => [e3, e4, e5], 
     27 => [e6, e7], 
     ... 
    } 

¡Gracias!

+1

Sus preguntas dice MongoDB/MongoId, pero mencionaste ActiveRecord. ¿Podría aclarar si está utilizando MongoId o ActiveRecord? –

+0

Correcto, quise decir objetos similares a ActiveRecord porque Mongoid refleja bastante bien la API de ActiveRecord. Editado – Adam

Respuesta

8

Después de más pensamiento y algo de ayuda de Forrst, se me ocurrió esto:

events.inject({}) do |memo,event| 
    (memo[event.time.day] ||= []) << event 
    memo 
end 

Rails Al parecer monkeypatches enumerables con un método #group_by que funciona así:

events.group_by { |event| event.time.day }