在 Ruby 中以编程方式构建多行字符串
这是我在编程时经常做的事情:
code = ''
code << "next line of code #{something}" << "\n"
code << "another line #{some_included_expression}" << "\n"
有没有比 << 更好的方法?每行都使用“\n”
或+“\n”
? 这看起来效率很低。
我对 Ruby 解决方案特别感兴趣。我在想类似的事情
code = string.multiline do
"next line of code #{something}"
"another line #{some_included_expression}"
end
Here's something I often do when programming:
code = ''
code << "next line of code #{something}" << "\n"
code << "another line #{some_included_expression}" << "\n"
Is there some better way than having << "\n"
or + "\n"
on every line? This seems quite inefficient.
I'm interested in Ruby solutions, in particular. I'm thinking something like
code = string.multiline do
"next line of code #{something}"
"another line #{some_included_expression}"
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您想要构建文本块,最简单的方法就是使用 % 运算符。例如:
“代码”将是
If you're looking to build a block of text, the easy way to do it is to just use the % operator. For example:
'code' will then be
这是一种方式:
This would be one way:
使用 <<- 运算符:
Use <<- operator:
我想,您只需在字符串中嵌入 ...\n" 就可以了。这是一种有趣的方法:
然后
这将启用类似的功能:
或者甚至:
It would work for you to just embed ...\n" in your strings, I suppose. Here is a fun way to do it:
then
This would enable something like:
Or even:
这是此处介绍的方法:
这是通过使用这个:
我想这个问题是:缺乏可移植性/猴子补丁的存在是否会使这个解决方案变得糟糕。
Here's a method presented here:
This is accomplished by using this:
I guess the question with this is: does the lack of portability / presence of monkey patching make this solution bad.
有什么问题:
What's wrong with:
您可以将多行文本放入一个文件中,并使用 ERB 来解析它(注意 ERB 包含在 Ruby 中)
(ERB 可以从 Binding 访问变量,Binding 是一个对象,提供对实例方法和变量的访问,这些实例方法和变量属于通过将其设置为“绑定”,它指向自身)
文档 这里。
You could place your multi-line text in a file, and use ERB to parse it (note ERB is included with Ruby)
(ERB can access variables from a Binding, an object that provides access to the instance methods and variables that are owned by another object. By setting it to "binding" it points to itself)
Documentation here.