Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby access multiple array elemenets by indexes (sub array)

Tags:

arrays

ruby

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..

like image 641
bliof Avatar asked Feb 02 '13 21:02

bliof


Video Answer


1 Answers

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.

like image 156
Samsinite Avatar answered Oct 20 '22 06:10

Samsinite