1

So I'm attempting to create a simple Ruby script that removes a specified number of fields from a csv file. First I am writing the csv file to an array and then passing that array to a delete_fields method. In the delete fields method I iterate over every column of every row and check whether or not the column falls between the range of fields required for deletion. At the moment it seems to be working for the first three fields and then hangs on the 4th.

Here is my Code:

    require 'csv'
    def read_csv( csv_file )

      arr_of_records = CSV.read( csv_file )


      return arr_of_records
    end

    def remove_fields ( csv_array, new_csv_file, start_field, end_field )
      #file = File.new(new_csv_file, "w")

      csv_array.each_with_index do |row, row_i | 
       row.each_with_index do |column, column_i| 

         column.delete_at(column_i) if ((column_i >= start_field) && (column_i <=     end_field))
         puts column

        end
       end
    end


    remove_fields( read_csv( ARGV[0] ), ARGV[1], ARGV[2].to_i, ARGV[3].to_i )

The error I get is as follows:

    ryan@Alfred:~$ ruby csv_read.rb test_data.csv altered_test_data.csv 3 8
    8
    ?
    ?
    csv_read.rb:16:in `remove_fields': undefined method `delete_at' for   "Lakewoodcity":CSV::Cell (NoMethodError)
from csv_read.rb:1:in `each_with_index'
from csv_read.rb:14:in `each'
from csv_read.rb:14:in `each_with_index'
from csv_read.rb:14:in `remove_fields'
from csv_read.rb:1:in `each_with_index'
from csv_read.rb:13:in `each'
from csv_read.rb:13:in `each_with_index'
from csv_read.rb:13:in `remove_fields'
from csv_read.rb:24

Any help much appreciated.

1
  • I've got it working using the slice! method with a range parameter. Will post solution in 7 hrs (new user) would still be interested to know why this didn't work. Sep 25, 2012 at 0:35

1 Answer 1

1

You're getting this error because you're calling delete_at on an object of type String instead of Array. What you really want to do is call delete_at on the row that you're currently iterating over and not the column. This should fix your problem:

  csv_array.each_with_index do |row, row_i | 
   row.each_with_index do |column, column_i| 

     row.delete_at(column_i) if ((column_i >= start_field) && (column_i <=     end_field))
     puts column

    end
   end

Something to help with understanding this is to think of the first block parameter as a value instead of a row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.