1

Using array.each_with_index returned an array containing the indexes of several elements which I set equal to a variable, indexes. I just want to know how I can then find the elements at each of those indexes like array[indexes] #=> element 1, element 2, etc. I tried the previous example with no luck, and also array[indexes.each {|x| x}].

Not sure why this is so hard, but I am brand new to coding and I couldn't find the answer elsewhere.

1
  • Give the code you have tried. Commented Sep 21, 2014 at 14:56

2 Answers 2

3

That is what Array#values_at is for:

indices = [0,2] 
p ["a", "b", "c", "a"].values_at(*indices) # => ["a", "c"]
Sign up to request clarification or add additional context in comments.

1 Comment

This actually is what I was looking for, and I allows me to do what I need. Thanks!
0

You are probably starting wrong.

each_with_index is meant to iterate over your array with an index like this:

array.each_with_index do |element, index|

 #do stuff with the element and the index here

end

If you already have your array of indexes and you really want to do it that way you can:

indexes.each do |index|

 array[index]

end

You should think of each as a for loop other the element, passing consecutivly each element to the variable in | |. Inside the { } or do ... end you can then do things with your element. It's not meant to be used like x = array.each :)

1 Comment

When I said I used array.each_with_index I just left off the rest of the the block I used to find which indexes I wanted. Should have left that to be clear. Your solution works, thank you greatly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.