gpt4 book ai didi

arrays - 当该范围是变量时,ruby 数组子范围

转载 作者:太空宇宙 更新时间:2023-11-03 17:47:23 24 4
gpt4 key购买 nike

是否可以像这样将子范围应用于 ruby​​ 中的数组:

 > array = [4, 3, 2, 1]
> array[0...2]
=> [4, 3]

如果[0...2]存储在变量中?我似乎无法获得语法来满足我的需求。什么取代了 <?>在下面,如果有的话?

 > array = [4, 3, 2, 1]
> range = [0...2]
> array<?>
=> [4, 3]

最佳答案

是的,当然!这样做:

array = [4, 3, 2, 1]
exclusive_range = [0...2] # Will get 0th and 1st element of the array
inclusive_range = [0..2] # Will get 0th, 1st and 2nd element of the array
array[exclusive_range.first]
# => [4, 3]
array[inclusive_range.first]
# => [4, 3, 2]

如果你想避免 .first 调用,你可以将你的范围放在一个变量中(而不是在一个数组中):

range = 0...2
array[range]
# => [4, 3]

关于arrays - 当该范围是变量时,ruby 数组子范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204577/

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