Ruby缩进多行字符串 [英] Ruby indented multiline strings

查看:80
本文介绍了Ruby缩进多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个最佳实践问题。有明显的方法可以做到这一点,但似乎没有一个是正确的。

It's a best-practice question. There are obvious ways to do that, none of them just seem quite right.

我经常需要测试是否生成了多行字符串。通常,这会破坏缩进,使所有内容看起来都一团糟:

Quite often I need to test that some multi-line string gets produced. This normally breaks indentation making everything look like a mess:

class TestHelloWorld < Test::Unit::TestCase
  def test_hello
    assert_equal <<EOS, hello_world
Hello, world!
  World greets you
EOS
  end
end

使用<<-我可以在此处缩进doc标记,但它不会在Heredoc内去除缩进,它仍然看起来很恐怖。

With <<- I can indent here doc marker, but it doesn't strip indentation inside heredoc, it still looks horrible.

class TestHelloWorld < Test::Unit::TestCase
  def test_hello
    assert_equal <<-EOS, hello_world
Hello, world!
  World greets you
    EOS
  end
end

这让我缩进了,但是测试线的可读性受到了影响。这个 gsub 确实在这里感觉不到。

This lets me indent but readability of test line suffers. This gsub really doesn't feel right here.

class TestHelloWorld < Test::Unit::TestCase
  def test_hello
    assert_equal <<-EOS.gsub(/^ {6}/, ""), hello_world
      Hello, world!
        World greets you
    EOS
  end
end

是否有任何方法可以测试这种真正可读的多行字符串?

Is there any way to test such multi-line strings that's really readable?

推荐答案

我个人认为Ruby的缩进heredocs是没用,它们应该像Bash缩进heredocs一样工作,并在字符串中去除空格

Personally, I think that Ruby's indented heredocs are useless and they should work more like Bash indented heredocs and also strip whitespace inside the string …

无论如何,有一些库试图处理这个问题情况。有很多库可以尝试解决此问题:

Anyway, there are a couple of libraries that try to deal with this situation. There is a wide array of libraries that try to fix this problem:

  • Martin Aumont's Unindent library which is also part of the Facets library
  • Facets also provides String#margin
  • Sunlight Labs' Unindentable library
  • Samuel Dana's Indentation library

这篇关于Ruby缩进多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆