是否可以在ruby中将子范围应用于数组:
> array = [4, 3, 2, 1]
> array[0...2]
=> [4, 3]
如果[0...2]
存储在变量中?我似乎无法获得一种语法来给我我想要的东西。如果有的话,取代以下<?>
的是什么?
> array = [4, 3, 2, 1]
> range = [0...2]
> array<?>
=> [4, 3]
答案 0 :(得分: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]
答案 1 :(得分:1)
请注意(0..2).size #=> 3
。如果您想要返回[4,3]
,则需要:
range = 0..1
您可以像这样使用它:
array[range] #=> [4, 3]
或者像这样:
array.values_at *range #=> [4, 3]