Ruby:写CSV如果条件满足 - Ruby: Write to CSV if condition met

- 此内容更新于:2016-02-01
主题:

我全新的Ruby和用它来读/写csv。到目前为止,我有一个脚本,该脚本如下:从CSV文件导入数据,存储选择列作为一个单独的数组(我不需要数据从每一列)上执行的计算数据,将结果存储在新创建的数组转置表行数组,输出到CSV目前,我能够输出表使用以下:我的问题是,我怎么能添加一个条件只输出行,结果等于某一文本字符串之一。例如,如果该值在result2等于“苹果”,我想要这一行中的数据写入到csv文件。如果不是,那么跳过这一行。我试着把if/else在几个不同的领域,没有任何的成功。感谢任何帮助

原文:

I am brand new to Ruby and using it to try to read/write to csv. So far, I have a script that does the following:

  1. Imports data from a CSV file, storing select columns as a separate array (I don't need data from every column)
  2. Performs calculations on the data, stores the results in newly created arrays
  3. Transposes the arrays to table rows, to be outputted to a csv

    table = [Result1, Result2, Result3].transpose
    

Currently, I am able to output the table using the following:

     CSV.open(resultsFile, "wb",
    :write_headers=> true,
    :headers => ["Result1", "Result2", "Result3"]
      ) do |csv|
      table.each do |row|
         csv << row 
      end

My question is, how can I add a conditional to only output rows where one of the results equals a certain text string. For example, if the value in result2 is equal to "Apple", I want the data in that row to be written to the csv file. If not, then skip that row.

I've tried placing if/else in a few different areas and have not had any success.

Thanks for any help

网友:存储的好处列分别是什么?

(原文:what's the benefit of storing the columns separately?)

楼主:@Tilocsv大约有40列,我只是感兴趣3(我编辑我的帖子让那块更清楚)。我打开有什么建议尽管——这是我第一次尝试了Ruby所以不知道我现在做的那部分。

(原文:@Tilo the csv has about 40 columns and I am only interested in 3 of them (I've edited my post to make that piece more clear). I am open to any suggestions though - this is the first time I've tried Ruby so not sure I'm doing that part right.)

解决方案:
你可以做类似下图:合并两个数组,数组的数组,其中每个赋从输入数组元素相同的索引,并且可以任意阵列的2-element数组转换成散列。例如:
原文:

You could do something like below:

header = ["Result1", "Result2", "Result3"]
CSV.open(resultsFile, "wb", :write_headers=> true, :headers => header) do |csv|
    table.each do |row|
        csv << row if header.zip(row).to_h["Result2"] == "Apple"
    end
end

zip merges two arrays and produces array of arrays where each sub-array has element from input arrays at same index, and to_h can convert any array of 2-element arrays into hash. For example:

row = ["Orange", "Apple", "Guava"]
header = ["Result1", "Result2", "Result3"]

header.zip(row).to_h
=> {"Result1"=>"Orange", "Result2"=>"Apple", "Result3"=>"Guava"}