gpt4 book ai didi

ruby - 如何比较数组中的值

转载 作者:数据小太阳 更新时间:2023-10-29 08:17:26 26 4
gpt4 key购买 nike

假设我有一个数组

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

我如何比较第一个值与第二个值,第二个值与第三个值等。

我唯一能想出的就是这个(相当难看)

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

我想要的是

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

是否有一种很好的“ ruby 方式”来实现这一点?无需使用所有丑陋的 array[i]array[i+1] 东西。

最佳答案

使用 Enumerable#each_cons :

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

关于ruby - 如何比较数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20218156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com