Robert Klemme
4/9/2007 2:19:00 PM
On 09.04.2007 15:46, Jason Madigan wrote:
> 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.
I think you would get [100,100] in your case (apart from the fact that
the array you present is an array of strings).
I think the most elegant solution is with #each_cons; with enumerator
you can do:
irb(main):007:0> (1..10).to_enum(:each_cons, 2).map {|a,b| b-a}
=> [1, 1, 1, 1, 1, 1, 1, 1, 1]
irb(main):008:0> [1000,1100,1200].to_enum(:each_cons, 2).map {|a,b| b-a}
=> [100, 100]
Kind regards
robert