Heredoc Method Chaining
This was the tip of the week in the June 10, 2021 Ruby Weekly Newsletter.
Ruby’s Heredocs allow us to easily write multiline strings, or big blocks of text. Oftentimes, when writing these heredocs, we need to do some sort of string manipulation. We often do this string manipulation as a separate method call after we’ve initialized the string using a heredoc. This might look something like:
string = <<~EOF
This is a multiline string
but we don't actually want
any newlines in the final version
EOF
string.gsub!("\n", " ")
=> "This is a multiline string but we don't actually want any newlines in the final version "
However, less well known is that we can actually call methods on the heredoc itself. As you may have noticed, syntactically this won’t work by calling the method after the closing identifier. Instead, any methods can be called right after the opening identifier. In this case, this would look like this:
string = <<~EOF.gsub("\n", " ")
This is a multiline string
but we don't actually want
any newlines in the final version
EOF
=> "This is a multiline string but we don't actually want any newlines in the final version "
We can also chain together methods on the heredoc in a similar fashion:
string = <<~EOF.gsub("\n", " ").upcase
This is a multiline string
but we don't actually want
any newlines in the final version
EOF
=> "THIS IS A MULTILINE STRING BUT WE DON'T ACTUALLY WANT ANY NEWLINES IN THE FINAL VERSION "
In the case above, we replaced the newlines with spaces and converted the string to upper case.