How can one conditionally remove whole columns from a 2D array in Ruby?

I have several large csv files with thousands of columns that I need to import and then delete all columns based on columns. Is there an easy way to handle this in Ruby?

I could transpose the data and then just delete the lines, but I was wondering if there is a more syntactically sweet way to do this.

+1


source to share


4 answers


You need to iterate over rows and delete columns with Array#slice!

.

Something like:



my_array.each do |row|
  row.slice!(3) if <insert condition>
end

      

should do it.

+2


source


As you need to assign all columns in the csv to columns in the database, you just need to ignore the columns you don't need in the csv. This blog post has a good example.



0


source


Snapshot in the dark, but if the criteria are simple enough and you can somehow sample the data to see which columns you need to remove, perhaps you can skip importing the columns in the first place, if at all possible it should be faster than slicing, which is is the way to go differently.

0


source


I ended up using transpose and then using reverse_each to work with the bottom edge of the string! on the lines to be deleted. Thanks for the help.

0


source







All Articles