Shane Carroll
Shane Carroll

Reputation: 37

Finding elements of an array with an array of indexes (Ruby)

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.

Upvotes: 1

Views: 78

Answers (2)

steenslag
steenslag

Reputation: 80065

That is what Array#values_at is for:

indices = [0,2] 
p ["a", "b", "c", "a"].values_at(*indices) # => ["a", "c"]

Upvotes: 3

dfherr
dfherr

Reputation: 1642

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 :)

Upvotes: 0

Related Questions