gpt4 book ai didi

ruby - 切片数组数组

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

样本数组,

# sub-arrays are all of the same length
arr = [[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]]

现在,

arr.some_slicing_technique(0..2)

应该给我,

[[1,2,3], [5,6,7], [2,4,6], [1,3,5]]

some_slicing_technique 是否存在?解决此问题的最佳方法是什么?

最佳答案

你可以这样做:

[[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]].map {|e| e.take(3)}

=> [[1, 2, 3], [5, 6, 7], [2, 4, 6], [1, 3, 5]]

或者如果你想使用范围:

[[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]].map {|e| e[0..2]}

关于ruby - 切片数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9088010/

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