使用ruby将数组拆分为'tables'

时间:2013-06-26 15:42:02

标签: arrays ruby csv

我似乎无法解决这个问题,对吧。

我在数组中有一个很大的单词列表。我希望这些单词出现在8个“表格”中,每个14行乘9行,每个列的每一列都有单词。

所以我可以到columns = words.each_slice(14)然后再tables = columns.each_slice(9),但从那里我不确定。我觉得我应该创建一个哈希并将每列的前n个项追加到数组中,然后可以使用制表符分隔符将它们连接起来。

我的目的地是电子表格,因此输出到CSV会有意义吗?我只是不确定如何将它分组为单独的“表”(而不是只有9列,有很多行而且没有分离)但是可能只需要一个带有所有空白的csv行?

无论如何,欢迎任何意见或见解。

2 个答案:

答案 0 :(得分:0)

这将按照您的要求进行

你没有说出你想要的输出格式,所以我只是用引号包围每个单词,用逗号连接它们并在表之间加一个空行。

我的“单词”只是数字1到200。

words = (1 .. 200).map { |v| '%03d' % v }

words.each_slice(14).each_slice(9) do |table|
  (0 ... table[0].size).each do |i|
    row = table.map { |column| column[i] }
    row.pop if row[-1].nil?
    puts row.map { |cell| %<"#{cell}"> }.join ','
  end
  puts ''
end

<强>输出

"001","015","029","043","057","071","085","099","113"
"002","016","030","044","058","072","086","100","114"
"003","017","031","045","059","073","087","101","115"
"004","018","032","046","060","074","088","102","116"
"005","019","033","047","061","075","089","103","117"
"006","020","034","048","062","076","090","104","118"
"007","021","035","049","063","077","091","105","119"
"008","022","036","050","064","078","092","106","120"
"009","023","037","051","065","079","093","107","121"
"010","024","038","052","066","080","094","108","122"
"011","025","039","053","067","081","095","109","123"
"012","026","040","054","068","082","096","110","124"
"013","027","041","055","069","083","097","111","125"
"014","028","042","056","070","084","098","112","126"

"127","141","155","169","183","197"
"128","142","156","170","184","198"
"129","143","157","171","185","199"
"130","144","158","172","186","200"
"131","145","159","173","187"
"132","146","160","174","188"
"133","147","161","175","189"
"134","148","162","176","190"
"135","149","163","177","191"
"136","150","164","178","192"
"137","151","165","179","193"
"138","152","166","180","194"
"139","153","167","181","195"
"140","154","168","182","196"

答案 1 :(得分:-1)

你走在正确的轨道上。这是一个以CSV格式写入长度为14 * 9倍数的列表的解决方案。您还可以使用相应的gem直接创建电子表格。我将发布一个很快处理任何长度列表的更新。

请注意,我认为each_slice要求您至少包含Enumerable至少2.0版之前的Ruby版本。

(0...14*9*2).each_slice(14).collect.each_slice(9) {|table|
  table.transpose.each {|row|
    puts row.inspect.delete('[]')} ; puts}

如果您需要将输入array填充到14 * 9的倍数以便transpose有效,则可以使用以下内容:

def print_csv(array)
  mod=array.length%(14*9)
  array = array+[nil]*(14*9-mod) if mod>0
  array.each_slice(14).collect.each_slice(9) {|table|
    table.transpose.each {|row|
      puts row.reject(&:nil?)*','} ; puts}
end