如何比较数组中的值

时间:2021-10-19 13:35:51

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.

有一种很好的“ruby方法”来实现这一点吗?不需要使用所有难看的数组[i]和数组[i+1]之类的东西。

2 个解决方案

#1


9  

Using Enumerable#each_cons:

使用# each_cons可列举的:

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

#2


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]

#1


9  

Using Enumerable#each_cons:

使用# each_cons可列举的:

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

#2


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]