Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all elements of a column in a two-dimensional array

I have this array:

arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]

which is representing a prawn-table containing columns "a", "b", and "c".

How do I remove the entire column "c" with all its values, 5, 8, 1?

Maybe there are useful hints in "Create two-dimensional arrays and access sub-arrays in Ruby" and "difficulty modifying two dimensional ruby array" but I can't transfer them to my problem.

like image 314
Madamadam Avatar asked May 21 '13 19:05

Madamadam


2 Answers

Just out of curiosity sake here is an another approach (one-liner):

arr.transpose[0..-2].transpose
like image 147
Torimus Avatar answered Oct 05 '22 06:10

Torimus


 arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]

 i = 2   # the index of the column you want to delete
 arr.each do |row|
   row.delete_at i
 end

  => [["a", "b"], [2, 3], [3, 6], [1, 3]] 

 class Matrix < Array
   def delete_column(i)
     arr.each do |row|
      row.delete_at i
     end
   end
 end
like image 22
Tilo Avatar answered Oct 05 '22 07:10

Tilo