On Thu, Mar 18, 2010 at 6:50 PM, Steve Wilhelm <steve / studio831.com> wrote:
> I have an array of records that contain timestamps at random intervals.
> The records are ordered by timestamp.
>
> I would like to convert the array into an array of arrays; each subarray
> would contain "grouped records." Grouping would occur if the timestamp
> of the next element in the original array is within thirty seconds of
> the current element.
>
> Example (second column is timestamp in seconds starting from zero).
>
> A 0, B 15, C 35, D 100, E 205, F 215, G 300
>
> would result in
>
> [[A, B, C], [D], [E, F], [G]]
>
> Any help on how to do this in the "Ruby Way" would be appreciated.

Here's another way:

require 'pp'
require 'set'

Struct.new("Record", :value, :timestamp)

data = [
  Struct::Record.new('A', 0),
  Struct::Record.new('B', 15),
  Struct::Record.new('C', 35),
  Struct::Record.new('D', 100),
  Struct::Record.new('E', 205),
  Struct::Record.new('F', 215),
  Struct::Record.new('G', 300),
]

pp data

pp data.
     to_set.
     divide{|i, j| (i.timestamp - j.timestamp.abs) < 30}.
     map{|s| s.to_a}

$ ruby -v z.rb
ruby 1.8.7 (2008-08-11 patchlevel 72) [universal-darwin10.0]
[#<struct Struct::Record value="A", timestamp=0>,
 #<struct Struct::Record value="B", timestamp=15>,
 #<struct Struct::Record value="C", timestamp=35>,
 #<struct Struct::Record value="D", timestamp=100>,
 #<struct Struct::Record value="E", timestamp=205>,
 #<struct Struct::Record value="F", timestamp=215>,
 #<struct Struct::Record value="G", timestamp=300>]
[[#<struct Struct::Record value="D", timestamp=100>],
 [#<struct Struct::Record value="G", timestamp=300>],
 [#<struct Struct::Record value="F", timestamp=215>,
  #<struct Struct::Record value="E", timestamp=205>],
 [#<struct Struct::Record value="A", timestamp=0>,
  #<struct Struct::Record value="C", timestamp=35>,
  #<struct Struct::Record value="B", timestamp=15>]]

(Depending on the amount of data converting from array to sets to
arrays may be expensive :-)