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..
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With