【发布时间】:2016-02-05 06:07:14
【问题描述】:
你如何有一个没有前导空格的多行字符串并且仍然与方法正确对齐?以下是我的一些尝试。工作的那个不是很好玩……
module Something
def welcome
"
Hello
This is an example. I have to write this multiline string outside the welcome method
indentation in order for it to be properly formatted on screen. :(
"
end
end
module Something
def welcome
"
Hello
This is an example. I am inside welcome method indentation but for some reason
I am not working...
".ljust(12)
end
end
module Something
def welcome
"Hello\n\n"+
"This is an example. I am inside welcome method indentation and properly"+
"formatted but isn't there a better way?"
end
end
更新
这是method from the ruby style guide:
code = <<-END.gsub(/^\s+\|/, '')
|def test
| some_method
| other_method
|end
END
# => "def test\n some_method\n other_method\nend\n"
【问题讨论】:
-
我认为你不能。这个stackoverflow.com/questions/2337510/… 可能会有所帮助
-
“好玩”有没有关系?是的!
-
我认为风格指南中的解决方案很好。尽管 Active Record 实现了
strip_heredoc,这减轻了痛苦,但它并不能缓解向块中添加新内容的长期问题。使用|可以很容易地看到边距在哪里。当多人在一个项目上工作时,很容易找到利润是一件好事。不过,我会稍微改变一下模式,改为/^\s*\|/,即使块没有从左边距缩进,它也能工作。
标签: ruby multilinestring