3

We have an array, say:

my_arr = [121, 23, 46, 91, 38, 140]

Also we have the array of indexes:

indxs = [1, 2, 4]

I know about values_at method, but it doesn't accept arrays, however, it can accept multiple values, proof: https://ruby-doc.org/core-2.5.1/Array.html#method-i-values_at

Maybe you could give me a clue how to deal with values_at. Thanks in advance!

EDIT: We've got 2 answers, so I I did a benchmark (1000 iterations, array.size = 20, indexes.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)

2 Answers 2

9

You can splat the array as below:

my_arr = [121, 23, 46, 91, 38, 140]
indxs = [1, 2, 4]
my_arr.values_at(*indxs)
# => [23, 46, 38]
Sign up to request clarification or add additional context in comments.

Comments

3

As alternative:

my_arr = [121, 23, 46, 91, 38, 140]
indxs = [1, 2, 4]

indxs.map { |i| my_arr[i] }
#=> [23, 46, 38]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.