From: Rick DeNatale Date: 2007-04-09T23:38:46+09:00 Subject: Re: Creating an array of differences On 4/9/07, Jason Madigan wrote: > Hey there, > > I'm pretty new to Ruby so perhaps some of you could help me out with a > little problem I've come up against. I have an array consisting of > integers (called session[:octets_in]). What I want to do is create an > array comprising of the difference between the current element and the > previous element (e.g. ["1000", "1100", "1200"] would become ["100", > "200"]). I'm not entirely sure how to go about this, so any pointers > would be welcome. Did you really mean that this would produce ["100", "100"]? since the element before "1200" is "1100" not "1000". require 'enumerator' ["1000", "1100", "1200", "1420"].enum_for(:each_cons, 2).map {|a, b| (b.to_i - a.to_i).to_s} => ["100", "100", "220"] If you really meant the difference between the second and subsequent elements and the first, then here's a tricksy way to to it: ["1000", "1100", "1200"].inject(nil) {|s,e| s ? s << (e.to_i - s.first.to_i).to_s : [e]}[1..-1] It stores the first element in the 'sum' being computed by inject, then strips it off. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/