0

Let's say I have an array

arry = ["a","b","c","d","e","f","g"]

and I want to get the fourth, second, and seventh element of that array.

Let's say some other function determined which are the needed values and passed me backan array of indices like [3, 1, 6]. In most languages I could write this

array[3,1,6] #=> ["d","b","g"] (or "dbg"?)

or

array[3 1 6] #=> ["d","b","g"]

But that won't work in Ruby, of course. Is there a simple way to do this in Ruby? The cleanest I can find is something like:

[3,1,6].map { |i| array[i] }

I really tried to find a duplicate to this question since it seems so basic, but I just couldn't.

This is remarkably easy to do in most languages, so I'm almost assuming I'm just overlooking the remarkably obvious.

2 Answers 2

6
array.values_at(3,1,6) #=> ["d","b","g"]
Sign up to request clarification or add additional context in comments.

1 Comment

Dang it. Knew it was something simple. Not as simple as just being a function of [] like I'd assumed, but this is just what I was looking for. Thanks!
0

If your other function returns an array then you must flatten it before you can pass it as parameters to values_at. Like this

arry = ["a","b","c","d","e","f","g"]

def indices
  [1,3,6]
end

puts arry.values_at(*indices)

output

b
d
g

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.