繁体   English   中英

如何在没有负索引的情况下迭代红宝石数组

[英]How to iterate the ruby array without negative indices

我需要将ruby数组中的每个值与上一个和下一个值进行比较。

更新资料

例:

[1,2,4,5]

我想这样检查。 (a[i] with a[i-1] and a[i+1])

1 with only next value  # as there is no prev value
2 with prev & next value
4 with prev & next value
5 with only prev value # as there is no next value

在红宝石中,a [-1]并不指向nil,而是取最后一个值。 因此,无法迭代。 有其他解决方法吗?

试过了

  1. 将数组更改为[nil,1,2,4,5,nil]

但出现以下错误

Fixnum与nil的比较失败(ArgumentError)

  1. 而不是0..n我尝试了1...n 但这不能解决我的问题。

题:

如何忽略ruby数组中first(i-1)和last(i + 1)元素的负索引。

您的比较没有任何意义。 您将所有内容进行了两次比较,但是如果有人在迭代时确实在更改数组,那么您将面临比这大得多的问题(当您已经在中间时,仍然无法捕获对数组开头所做的修改)。 比较每对连续的元素就足够了,这很容易做到:

[1, 2, 4, 5].each_cons(2).all? {|a, b| a < b }

如果您真的必须比较三元组,那也很容易做到:

[1, 2, 4, 5].each_cons(3).all? {|a, b, c| a < b && b < c }

如果要使滑动窗口的大小通用,则可以执行以下操作:

[1, 2, 4, 5].each_cons(n).all? {|window| 
  window.each_cons(2).map {|a, b| a < b }.inject(:&) 
}

我需要将ruby数组中的每个值与上一个和下一个值进行比较。

此方法采用数组和比较方法,例如:<:>:==

def prev_next arr, com
  arr.map.with_index { |e,i|
    if i == 0
      [ e,
        e.send(com,arr[i.succ])
      ]
    elsif i == arr.length-1
      [ e.send(com,arr[i.pred]),
        e
      ]
    else
      [ e.send(com,arr[i.pred]),
        e, 
        e.send(com,arr[i.succ])
      ]
    end
  }
end

arr = [1,2,3,4,5]
p prev_next(arr,:<)
#=> [[1, true], [false, 2, true], [false, 3, true], [false, 4, true], [false, 5]]

请注意,第二个参数可以作为字符串或符号传递,因为send足够聪明,可以将字符串转换为符号。

值得注意的方法: Object#sendFixnum#succInteger#pred

现在,我在这里完全同意Jörg的观点,即each_conseach_cons的方法,如果比较数据如此复杂,您可能应该寻找数据的其他结构。

照这样说。 没有什么可以阻止在Ruby中进行常规索引查找,并且如果没有其他效果,只需在一个简单的case语句中实现您的要求即可:

my_array = [1,2,4,5]

my_array.size.times do |ix|
    case ix
      when 0 then my_array[ix] == my_array[ix+1]
      when my_array.size-1 then my_array[ix] == my_array[ix-1]
      else my_array[ix-1] == my_array[ix] == my_array[ix+1]
    end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM