0

对于微阵列数据处理,我需要列出从 1 到 654 的基因名称,例如Gene_1 ... Gene_654.

我的简单 Ruby 代码生成以下内容:

1.upto(654).each { |i| print "Gene" } 

结果是:

GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene

GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene
..................................
GeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGeneGene=> 1
irb(main):008:0>

如何按顺序增量顺序将“后缀 _#”添加到打印的字符串并将它们放在一列中,例如:

Gene_1
Gene_2
::::::
Gene_654
4

3 回答 3

0

我会使用:

str = 'Gene_0'
654.times { puts str.next! }

哪个输出:

Gene_1
...
Gene_654

如果您需要相同宽度的文本输出,可能是因为您要将信息附加到每一行,请使用一些格式

str = 'Gene_0'
654.times { puts '%8s ' % str.next! }
# >>   Gene_1 
...
# >>   Gene_9 
# >>  Gene_10 
...
# >>  Gene_99 
# >> Gene_100 
...
# >> Gene_654 

如果您需要跨页面的列:

str = 'Gene_0'
654.times { print '%8s ' % str.next! }
puts

将它们分隔成 8 个空间宽的列。

默认情况下%8s使用右对齐,这并不总是你想要的。相反,您可以使用%-8s左对齐。

您可以构建一个包含列标题的数组:

str = 'Gene_0'
columns = []
654.times { columns << '%-8s' % str.next! }
puts columns.join(' ')

你甚至可以使用类似的东西inject

str = 'Gene_0'
columns = []
(1..654).inject(columns) { |a, i| a.push('%-8s' % str.next!) }
puts columns.join(' ')

但这开始添加并没有真正帮助的代码。


OP问:

...如何将“”添加到结果中...

上面的输出不容易看到自动附加到输出的空格'%8s ',所以我调整了格式字符串,通过将输出用双引号括起来使其更明显:

str = 'Gene_0'
654.times { puts '"%8s "' % str.next! }

这是相应的输出,经过精简以显示格式字符串如何随着字符串值的增加而保持列宽:

# >> "  Gene_1 "
...
# >> "  Gene_9 "
# >> " Gene_10 "
...
# >> " Gene_99 "
# >> "Gene_100 "
...
# >> "Gene_654 "

如果您希望所有空白都出现在列的末尾,请使用左对齐:

str = 'Gene_0'
654.times { puts '"%-8s "' % str.next! }

哪个输出:

# >> "Gene_1   "
...
# >> "Gene_9   "
# >> "Gene_10  "
...
# >> "Gene_99  "
# >> "Gene_100 "
...
# >> "Gene_654 "
于 2013-09-04T18:28:34.993 回答
0

编辑以符合新要求:

1.upto(654).each { |i| puts "Gene_#{i}" } 

--output:--
Gene_1 
Gene_2 
...
Geen_654
于 2013-09-04T18:19:54.690 回答
0
1.upto(654).each { |i| printf "%8s\t", "Gene_#{i}" }

来源:http ://www.ruby-doc.org/core-2.0.0/Kernel.html#format-method

于 2013-09-04T17:30:24.070 回答