2

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.

2 Answers 2

9

Using Enumerable#each_cons:

array = [1,2,3,4,5]
array.each_cons(2).map { |a,b| a - b }
# => [-1, -1, -1, -1]
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.