所以我试图创建一个简单的 Ruby 脚本,从 csv 文件中删除指定数量的字段。首先,我将 csv 文件写入一个数组,然后将该数组传递给 delete_fields 方法。在删除字段方法中,我遍历每一行的每一列,并检查该列是否落在删除所需的字段范围之间。目前它似乎在前三个领域工作,然后在第四个领域挂起。
这是我的代码:
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 )
我得到的错误如下:
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
非常感谢任何帮助。