根据条件切片,else return 空数组

Slicing based on a condition, else return empty array

比方说,我有一个数组:arr = [12, 34, 56, 38, 29, 91 ...] 和另一个数组:indices = [ i: i is positive int ],其中 indices.size 可以为零。

现在,

I want to slice arr starting from the index i, where i is the max. value of indices. If indices is empty, then return empty array, []

我试过以下方法:

arr[ indices.max .. -1 ]

indices 不为空时有效,但当它为空时会抛出错误:undefined method '+' for nil:NilClass,所以我尝试了另一个切片,例如

arr[ (indices + [-1]).max .. -1 ] # returns last item when indices is empty
# or
arr[ (indices + [-1]).max ... -1 ] # skips last item when indices isn't empty

如何正确地做到这一点? (也许在一行中)

你的主要问题是索引是空的。我会检查 indices.max 是否不为空,然后使用您的代码片段。示例:

indices.empty? ? [] : arr[ indices.max .. -1 ]

如果你使用它,你必须先满足一些前提条件:

  • arr 不为零
  • 索引不为零

您可以使用数组的大小作为后备:

arr[(indices.max || arr.size)..-1]