【发布时间】:2015-03-03 02:12:25
【问题描述】:
我正在尝试搜索两个多维数组以查找给定子数组中的任何共同元素,然后将结果放入第三个数组中,其中具有相似元素的整个子数组组合在一起(不仅仅是相似元素)。
数据从两个 CSV 导入:
require 'csv'
array = CSV.read('primary_csv.csv')
#=> [["account_num", "account_name", "primary_phone", "second_phone", "status],
#=> ["11111", "John Smith", "8675309", " ", "active"],
#=> ["11112", "Tina F.", "5551234", "5555678" , "disconnected"],
#=> ["11113", "Troy P.", "9874321", " ", "active"]]
# and so on...
second_array = CSV.read('customer_service.csv')
#=> [["date", "name", "agent", "call_length", "phone", "second_phone", "complaint"],
#=> ["3/1/15", "Mary ?", "Bob X", "5:00", "5551234", " ", "rude"],
#=> ["3/2/15", "Mrs. Smith", "Stew", "1:45", "9995678", "8675309" , "says shes not a customer"]]
# and so on...
如果primary.csv 和customer_service.csv 的子数组中存在任何数字作为元素,我希望将整个子数组(而不仅仅是公共元素)放入第三个数组results_array。基于上述示例的期望输出为:
results_array = [["11111", "John Smith", "8675309", " ", "active"],
["3/2/15", "Mrs. Smith", "Stew", "1:45", "9995678", "8675309" , "says shes not a customer"]] # and so on...
然后我想将数组导出到一个新的 CSV,其中每个子数组都是它自己的 CSV 行。我打算通过将每个子数组与 , 连接来迭代每个子数组,使其以逗号分隔,然后将结果放入新的 CSV:
results_array.each do {|j| j.join(",")}
File.open("results.csv", "w") {|f| f.puts results_array}
#=> 11111,John Smith,8675309, ,active
#=> 3/2/15,Mrs. Smith,Stew,1:45,9995678,8675309,says shes not a customer
# and so on...
我怎样才能达到预期的输出?我知道最终产品会看起来很乱,因为类似的数据(例如电话号码)将位于不同的列中。但我需要找到一种方法将数据分组在一起。
【问题讨论】:
-
不清楚你所说的“放入一个“空白”数组......”
-
分组之间的空子数组。 (诚然,主要问题的次要问题。)
标签: ruby arrays multidimensional-array