Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]
}
like image 341
CookieOfFortune Avatar asked Jan 23 '23 09:01

CookieOfFortune


2 Answers

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.

like image 132
Avdi Avatar answered Jan 25 '23 22:01

Avdi


last=0
new = old.map{|v|x=v-last;last=v;x}[1..-1]
like image 37
AShelly Avatar answered Jan 25 '23 23:01

AShelly