如何从基于Ruby中的索引的数组中获取多个值?

Ale*_*org 2 ruby arrays

我们有一个数组,说:

my_arr = [121, 23, 46, 91, 38, 140]
Run Code Online (Sandbox Code Playgroud)

我们还有索引数组:

indxs = [1, 2, 4]
Run Code Online (Sandbox Code Playgroud)

我知道values_at方法,但是它不接受数组,但是它可以接受多个值,证明:https : //ruby-doc.org/core-2.5.1/Array.html#method-i-values_at

也许您可以给我一个如何处理的线索values_at。提前致谢!

编辑:我们有2个答案,所以II做了一个基准测试(1000次迭代,array.size = 20,indexs.size = 4)

                  user     system      total        real
values_at       0.004502   0.000000   0.004502 (  0.004476)
map[i]          0.005878   0.000000   0.005878 (  0.006968)
Run Code Online (Sandbox Code Playgroud)

Md.*_*mon 6

您可以按以下方式展开阵列:

my_arr = [121, 23, 46, 91, 38, 140]
indxs = [1, 2, 4]
my_arr.values_at(*indxs)
# => [23, 46, 38]
Run Code Online (Sandbox Code Playgroud)