We recently decided at my job to a ruby style guide. One of the edicts is that no line should be wider than 80 characters. Since this is a Rails project, we often have strings that are a little bit longer - i.e. "User X wanted to send you a message about Thing Y" that doesn't always fit within the 80 character style limit.
I understand there are three ways to have a long string span multiple lines:
- HEREDOC
- %Q{}
- Actual string concatenation.
However, all of these cases end up taking more computation cycles, which seems silly. String concatenation obviously, but for HEREDOC
and %Q
I have to strip out the newlines, via something like .gsub(/\n$/, '')
.
Is there a pure syntax way to do this, that is equivalent to just having the whole string on one line? The goal being, obviously, to not spend any extra cycles just because I want my code to be slightly more readable. (Yes, I realize that you have to make that tradeoff a lot...but for string length, this just seems silly.)
Update: Backslashes aren't exactly what I want because you lose indentation, which really affects style/readability.
Example:
if foo
string = "this is a \
string that spans lines"
end
I find the above a bit hard to read.
EDIT: I added an answer below; three years later we now have the squiggly heredoc.
Maybe this is what you're looking for?
Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.
Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc
I had this problem when I try to write a very long url, the following works.
Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.
Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.
I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:
where
name = 'fred'
this producesIt's a nice day "fred" for a walk!
You can use
\
to indicate that any line of Ruby continues on the next line. This works with strings too:will output
"this is a string that spans lines"