From: James Edward Gray II Date: 2007-04-09T23:16:52+09:00 Subject: Re: Creating an array of differences On Apr 9, 2007, at 8:46 AM, Jason Madigan wrote: > Hey there, Hello. > I'm pretty new to Ruby so perhaps some of you could help me out with a > little problem I've come up against. Sure. Welcome to Ruby. > 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"]). Hmm, your description and your example don't say the same thing. I'll assume you meant the answer should be ["100", "100"]. > I'm not entirely sure how to go about this, so any pointers > would be welcome. With just core Ruby you could do: >> data = %w[1000 1100 1200] => ["1000", "1100", "1200"] >> (1..(data.size - 1)).inject(Array.new) do |diffs, i| ?> diffs + [(data[i - 1].to_i - data[i].to_i).abs.to_s] >> end => ["100", "100"] However, I think it looks a little prettier if you load a standard library and solve it like this: >> require "enumerator" => true >> data.enum_cons(2).map { |l, r| (l.to_i - r.to_i).abs.to_s } => ["100", "100"] Hope that helps. James Edward Gray II