4

Trivial using a for loop or each_with_index, just wondering if there was a better way of doing it using Ruby syntax.

I need to create a new array that is the derivative of the source array, eg:

for(int i = 1; i < oldArray.length; i++)
{
    newArray[i] = oldArray[i] - oldArray[i-1]
}
Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
CookieOfFortune
  • 13,836
  • 8
  • 42
  • 58

2 Answers2

8
old_array.each_cons(2).map{|x, y| y - x}

Enumerable#each_cons called with with a chunk size of 2 but without a block returns an Enumerator which will iterate over each pair of consecutive elements in old_array. Then we just use map to perform a subtraction on each pair.

Avdi
  • 18,340
  • 6
  • 53
  • 62
  • I just ran it on [1,2,3,4] and I get [1,1,1]. – Avdi Jul 31 '09 at 20:24
  • Are you sure you're not thinking of each_slice? That would give [1,1]. – Avdi Jul 31 '09 at 20:25
  • 2
    the code as it is written requires 1.8.7 i believe. however, you can write it as "old_array.enum_cons(2).map{|x, y| y - x}" and it will work on previous versions too – newacct Jul 31 '09 at 20:29
1
last=0
new = old.map{|v|x=v-last;last=v;x}[1..-1]
AShelly
  • 34,686
  • 15
  • 91
  • 152