Calculate the derivative ([i] - [i - 1]) in Ruby
-
06-07-2019 - |
Question
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.
OTHER TIPS
last=0
new = old.map{|v|x=v-last;last=v;x}[1..-1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow