Ruby:如果条件满足,写入CSV [英] Ruby: Write to CSV if condition met

查看:270
本文介绍了Ruby:如果条件满足,写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是全新的Ruby,并使用它来尝试读/写csv。到目前为止,我有一个脚本执行以下操作:


    从CSV文件导入数据,将选择列存储为单独的数组
  1. 将数组转换为数组,不需要每一列都有数据。


  2. <表格行,输出到csv

      table = [Result1,Result2,Result3] .transpose 


目前,我可以使用以下输出表: / p>

  CSV.open(resultsFile,wb,
:write_headers => true,
:headers => [Result1,Result2,Result3]
)do | csv |
table.each do | row |
csv<<我的问题是,我如何添加一个条件只有输出行在哪里?其中一个结果等于某个文本字符串。例如,如果result2中的值等于Apple,我想将该行中的数据写入csv文件。



我试过将if / else放在几个不同的区域,并且没有成功。



感谢您的帮助

解决方案

您可以执行以下操作:

  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 合并两个数组并生成数组数组,其中每个子数组都有元素输入数组在同一索引, to_h 可以将任何2元素数组的数组转换为哈希。例如:

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

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


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

解决方案

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"}

这篇关于Ruby:如果条件满足,写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆