Peter Peter - 2 months ago 8
Ruby Question

Building multi-line strings, programatically, in Ruby

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

Jim Jim
Answer

This would be one way:

code = []
code << "next line of code #{something}"
code << "another line #{some_included_expression}"
code.join("\n")