Ruby缩进多行字符串

参见英文答案 > How do I remove leading whitespace chars from Ruby HEREDOC?11
这是一个最佳实践的问题.有明显的方法可以做到这一点,没有一个似乎是对的.

很多时候我需要测试一些多行字符串的生成.这通常会打破缩进,使一切看起来像一团糟:

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

使用< - 我可以缩进这里的doc标记,但它不会剥离heredoc内的缩进,它仍然看起来可怕.

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

这让我缩进,但测试线的可读性受损.这个gsub真的不​​觉得这里.

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

有没有办法测试这样的多行字符串真的可读?

解决方法

就个人而言,我认为Ruby的缩进的heredocs是无用的,他们应该更像Bash缩进heredocs,并在字符串中空白的空格

无论如何,有几个图书馆试图处理这种情况.有各种各样的库试图解决这个问题:

> Martin Aumont’s Unindent library也是the Facets library的一部分
> Facet还提供String#margin
> Sunlight Labs’ Unindentable library
> Samuel Dana’s Indentation library

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...