19

I have an array and I have an array with indexes of certain elements from the first array. What is the best way to get the elements from the first array?

I am doing:

result = []
indexes.each { |current| result << my_array[current] }

But there should be a better way..

1 Answer 1

44

You can use Array#map:

indexes.map { |i| my_array[i] }

Or even better, Array#values_at

my_array.values_at(*indexes)

Where the * symbol extracts the array into arguments that get passed to the method.

Sign up to request clarification or add additional context in comments.

2 Comments

I knew I was missing something 10x :)
values_at is the fastest, by the way. By benchmark results it is ~ 2x faster than map and push, nevertheless, it's less 'human'.

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.