views:

217

answers:

2

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]
}
+1  A: 
last=0
new = old.map{|v|x=v-last;last=v;x}[1..-1]
AShelly
+5  A: 
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.

Avdi
I just ran it on [1,2,3,4] and I get [1,1,1].
Avdi
Are you sure you're not thinking of each_slice? That would give [1,1].
Avdi
sorry AShelly, this answer works better.
CookieOfFortune
the code as it is written requires 1.8.7 i believe. however, you can write it as "old_array.enum_cons(2).map{|x, y| y - x}" and it will work on previous versions too
newacct