尝试从数组中删除字符串时未定义的方法“delete_at”

时间:2012-09-25 00:03:46

标签: ruby multidimensional-array nomethoderror

所以我试图创建一个简单的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

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:0)

您收到此错误是因为您在delete_at类型的对象而不是String上调用了Array。您真正想要做的是在您当前正在迭代的delete_at上致电row而不是column。这应该可以解决您的问题:

  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

有助于理解这一点的是将第一个块参数视为value而不是row