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]
}
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.
last=0
new = old.map{|v|x=v-last;last=v;x}[1..-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With