如何通过Ruby中的索引从Array获取多个值

iro*_*and 1 ruby arrays

有一个数组a = %w(a b c d e),并希望通过索引获取第二个和最后一个值.

我可以得到价值a[1], a[-1],但我需要写a两次.有没有办法获得一个数组a.at(1, -1)

Aru*_*hit 8

是的可能.使用Array#values_at方法.

返回一个数组,其中包含与给定选择器对应的self元素.选择器可以是整数索引或范围.

a = %w{ a b c d e f }
a.values_at(1, 3, 5)          # => ["b", "d", "f"]
a.values_at(1, 3, 5, 7)       # => ["b", "d", "f", nil]
Run Code Online (Sandbox Code Playgroud)

这是你的例子: -

2.1.0 :001 > a = %w(a b c d e)
 => ["a", "b", "c", "d", "e"] 
2.1.0 :002 > a.values_at(1,-1)
 => ["b", "e"] 
2.1.0 :003 > 
Run Code Online (Sandbox Code Playgroud)