user7055375
user7055375

Reputation:

How do I take the nth element of multiple arrays?

I'm using Ruby 2.4. I have an array of arrays, and I want to grab the nth element of each of those arrays (starting with the "startIndex" array) and then form an array out of that. So I have

  row_data = []
  data_cols[startIndex..(data_cols.size)].each do |data_col|
    row_data.push(data_col[row]) 
  end

Although the above works, it seems like more code than I need. Is there a shorter way to write this?

Upvotes: 1

Views: 298

Answers (3)

Eric Duminil
Eric Duminil

Reputation: 54313

With your variable names, this would be a shorter version of your code :

data_cols.drop(startIndex).map{ |data_col| data_col[row] }

Upvotes: 0

codeforester
codeforester

Reputation: 43109

How about:

new_arr = Array.new
arr[startIndex..endIndex].each do |a|
  new_arr << a[n - 1]
end

Upvotes: 0

Richard Hamilton
Richard Hamilton

Reputation: 26444

All you need to do is

arr[start..finish].map { |a| a[n - 1] }

Example, let's say you had a multi-dimensional array like so

arr = [[4,6,5],[3,4,7],[9,1,2]];

And you wanted to find the middle element in each array, starting from the first index. You would do this

arr[1..2].map { |a| a[1] };
=> [4,1]

If you would like to store this in a new variable you would prefix the above line with var =

If you want to destructively modify the array, use map! instead

Upvotes: 3

Related Questions