gpt4 book ai didi

ruby - 在 Ruby 中以编程方式构建多行字符串

转载 作者:数据小太阳 更新时间:2023-10-29 06:33:38 26 4
gpt4 key购买 nike

这是我在编程时经常做的事情:

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

最佳答案

如果您要构建一个文本 block ,最简单的方法就是使用 % 运算符。例如:

code = %{First line
second line
Third line #{2 + 2}}

然后“代码”将是

"First line\n second line\n Third line 4"

关于ruby - 在 Ruby 中以编程方式构建多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1552598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com