ananyo2012
ananyo2012

Reputation: 63

collect all elements and indices of an array in two separate arrays in Ruby

Suppose I have an array array = [1,2,3,4,5]

I want to collect all the elements and indices of the array in 2 separate arrays like

[[1,2,3,4,5], [0,1,2,3,4]]

How do I do this using a single Ruby collect statement?

I am trying to do it using this code

array.each_with_index.collect do |v,k|
  # code
end

What should go in the code section to get the desired output?

Upvotes: 0

Views: 399

Answers (3)

ananyo2012
ananyo2012

Reputation: 63

I like the first answer that was posted a while ago. Don't know why the guy deleted it.

array.each_with_index.collect { |value, index| [value,index] }.transpose

Actually I am using an custom vector class on which I am calling the each_with_index method.

Upvotes: 1

grail
grail

Reputation: 930

Or even simpler:

[array, array.each_index.to_a]

Upvotes: 1

Jordan Running
Jordan Running

Reputation: 106027

Here's one simple way:

array = [1,2,3,4,5]
indexes = *array.size.times
p [ array, indexes ]
# => [[1, 2, 3, 4, 5], [0, 1, 2, 3, 4]]

See it on repl.it: https://repl.it/FmWg

Upvotes: 0

Related Questions