Calculate the derivative ([i] - [i - 1]) in Ruby

The trivial use of a for loop or each_with_index is just wondering if there was a better way to do this using Ruby syntax.

I need to create a new array that is a derivative of the original array, for example:

for(int i = 1; i < oldArray.length; i++) { newArray[i] = oldArray[i] - oldArray[i-1] } 
+4
source share
2 answers
 old_array.each_cons(2).map{|x, y| y - x} 

Enumerable#each_cons , called with a block size of 2, but without a block, returns an Enumerator that will old_array over each pair of consecutive elements in old_array . Then we just use map to do the subtraction for each pair.

+8
source
 last=0 new = old.map{|v|x=v-last;last=v;x}[1..-1] 
+1
source

All Articles