如何最好地包装 Ruby optparse 代码和输出?

How to best wrap Ruby optparse code and output?

对于以下代码,根据样式指南,它应该以 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)

如何巧妙地实现这一点?

在这种情况下,最简单的解决方案是像这样堆叠参数:

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

但在这种情况下效果不佳,因为描述字符串是自动缩进的。

所以我认为解决方案是遵循 Ruby Style Guide:

When using heredocs for multi-line strings keep in mind the fact that they preserve leading whitespace. It's a good practice to employ some margin based on which to trim the excessive whitespace.

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