Biketire
Biketire

Reputation: 2069

How to compare values in an Array

Let's say I have an array

array = [1,2,3,4,5]

How do I compare the first with the second value, the second with the third etc.

The only thing I could come up with is this (which is rather ugly)

compared = array.each_with_index.map do |a,i| 
  array[i+1].nil? ? nil : array[i] - array[i + 1]
end

compared.compact # to remove the last nil value

What I want is

[-1, -1, -1, -1]

Is there a nice "ruby way" of achieving this? without using all the ugly array[i] and array[i+1] stuff.

Upvotes: 2

Views: 154

Answers (2)

uncutstone
uncutstone

Reputation: 408

You can also use Enumerable#inject:

a = [1,2,3,4,5]
b = []
a.inject{|i,j| b<< i-j; j}
p b 

result:

[-1, -1, -1, -1]

Upvotes: 1

falsetru
falsetru

Reputation: 368944

Using Enumerable#each_cons:

array = [1,2,3,4,5]
array.each_cons(2).map { |a,b| a - b }
# => [-1, -1, -1, -1]

Upvotes: 9

Related Questions