Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You say you want to group by how close they are to each other. What you want is to group by a subset of the #created_at value, thus:</p> <pre><code>require "rubygems" require "active_support/core_ext/array" require "ostruct" require "pp" o1 = OpenStruct.new(:created_at =&gt; Time.local(2010, 11, 24, 20, 1, 0, 0)) o2 = OpenStruct.new(:created_at =&gt; Time.local(2010, 11, 24, 20, 2, 0, 0)) o3 = OpenStruct.new(:created_at =&gt; Time.local(2010, 11, 24, 20, 6, 0, 0)) o4 = OpenStruct.new(:created_at =&gt; Time.local(2010, 11, 24, 20, 13, 0, 0)) a = [o1, o2, o3, o4] grouped = a.group_by do |obj| time = obj.created_at Time.local(time.year, time.month, time.day, time.hour, (time.min / 5).floor, 0) end pp grouped.map {|val, arr| [val, arr.map {|obj| obj.created_at.to_s }] } </code></pre> <p>Which returns:</p> <pre><code>$ ruby a.rb [[Wed Nov 24 20:02:00 -0500 2010, ["Wed Nov 24 20:13:00 -0500 2010"]], [Wed Nov 24 20:00:00 -0500 2010, ["Wed Nov 24 20:01:00 -0500 2010", "Wed Nov 24 20:02:00 -0500 2010"]], [Wed Nov 24 20:01:00 -0500 2010, ["Wed Nov 24 20:06:00 -0500 2010"]]] </code></pre> <p>The first value of each enclosed Array is the key (minute in groups of 5 minutes), and the values are the actual ActiveRecord objects. For readability, I've mapped to the String version of Time, but it's the same idea.</p> <p>Also remember that #group_by generates an Array ordered the same as the original Array, thus your ordering constraints are kept - you don't need to resort the Array.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload