0

我似乎无法理解这一点,对吧。

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

所以我可以尽可能远columns = words.each_slice(14),然后再晚一点tables = columns.each_slice(9),但从那里我不确定。我觉得我应该做一个散列并将每列的第一个 n 项附加到一个数组中,然后可能用制表符分隔符将它们连接起来。

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

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

4

2 回答 2

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"
于 2013-06-26T16:37:32.597 回答
-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
于 2013-06-26T17:36:45.897 回答