gpt4 book ai didi

ruby - Array#slice(index, length) 当index+length超出范围时,取数组开头的元素

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:41 25 4
gpt4 key购买 nike

我正在寻找一种紧凑且可读的方式来使用索引和长度对数组进行切片,但是当索引 + 长度超出范围时,而不是像在数组末尾那样停止


[ "a", "b", "c", "d", "e"].slice(4, 3) #=> ["e"]

我想获取数组开头的元素:


#=> ["e", "a", "b"]

最佳答案

你可以这样做:

index = 4
length = 3
[ "a", "b", "c", "d", "e" ].cycle.take(index + length).last(length)

关于ruby - Array#slice(index, length) 当index+length超出范围时,取数组开头的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564300/

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