Search code examples
rubyenumerable

ruby pick (select) indices from collection


I have an array a. I want to build a new array with one or more of its elements picked out. The resulting array should look like:

 [a[5], a[7], a[8]]

How can I do this selection by passing the array of indices [5,7,8]? I imagined something like:

 b = a.select([5,7,8])

which doesn't work; select needs a block to evaluate. I could enumerate over the array and pick manually, but I have the feeling this should be possible more elegantly.


Solution

  • Use Array#values_at.

    b = a.values_at(*[5,7,8])