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

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



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:, "wb",
    :write_headers=> true,
    :headers => ["Result1", "Result2", "Result3"]
      ) do |csv|
      table.each do |row|
         csv << row 

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?)


(原文:@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.)


You could do something like below:

header = ["Result1", "Result2", "Result3"], "wb", :write_headers=> true, :headers => header) do |csv|
    table.each do |row|
        csv << row if["Result2"] == "Apple"

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"]
=> {"Result1"=>"Orange", "Result2"=>"Apple", "Result3"=>"Guava"}