Search code examples
rubyalgorithmderivative

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]
}

Solution

  • 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.