对于以下代码,根据样式指南应该包含80个字符:
opts.on('--scores_min <uint>', Integer, 'Drop reads if a single position in ',
'the index have a quality score ',
'below scores_main (default= ',
"#{DEFAULT_SCORE_MIN})") do |o|
options[:scores_min] = o
end
结果输出为:
--scores_min <uint> Drop reads if a single position in
the index have a quality score
below scores_main (default=
16)
哪个包裹在72个字符并且看起来不对:o(
我真的希望它包裹在80个字符并且像这样对齐:
--scores_min <uint> Drop reads if a single position in the
index have a quality score below
scores_min (default=16)
如何以聪明的方式实现这一目标?
答案 0 :(得分:1)
在这种情况下,最简单的解决方案是堆叠如下参数:
opts.on('--scores_min <uint>',
Integer,
"Drop reads if a single position in the ",
"index have a quality score below ",
"scores_min (default= #{DEFAULT_SCORE_MIN})") do |o|
options[:scores_min] = o
end
这导致了相当令人愉快的输出:
--scores_min <uint> Drop reads if a single position in the
index have a quality score below
scores_min (default= 16)
更一般地说,here docs可以更容易地以在代码和输出中看起来都很好的方式格式化输出字符串:
# Deeply nested code
puts <<~EOT
Drop reads if a single position in the
index have a quality score below
scores_min (default= #{DEFAULT_SCORE_MIN})
EOT
但是在这种情况下它不能很好地工作,因为描述字符串是自动缩进的。
答案 1 :(得分:0)
所以我认为解决方案是遵循Ruby Style Guide:
当使用heredocs用于多行字符串时请记住这一事实 他们保留领先的空白。雇用一些人是一种很好的做法 基于哪个边缘修剪过多的空白。
code = <<-END.gsub(/^\s+\|/, '')
|def test
| some_method
| other_method
|end
END
# => "def test\n some_method\n other_method\nend\n"
[编辑]在Ruby 2.3中你可以做(同样的参考):
code = <<~END
def test
some_method
other_method
end
END