How to use Here Documents In Ruby
Here Documents enable one to define multiple line strings. They start with << followed by a delimiter, usually a string or identifier format. A Here Documents does not interpret escape sequences so you can include single or double quotes without an escape sequence.
Example:
string_with_single_quote = <<~STR
She said 'Hello'
STR
string_with_double_quote = <<~STR
He said "Hi"
STR
puts string_with_single_quote
puts string_with_double_quote
Output
She said 'Hello' He said "Hi"
Conclusion:
Thus, all these methods will give the desired output, choosing them depends upon specific use case and user’s coding style.
How to Escape single and double quotes in a string in Ruby?
To handle strings containing single or double quotes in Ruby is not simple since putting these characters themselves within the string may also present difficulties. Your codes can give a syntax error or work in a way unintended just because of unescaped quotes. Luckily, Ruby has different ways to escape these symbols inside the text. This article will delve into three common methods to Escape single and double quotes in a string.
Table of Content
- Using Backslashes (\):
- Using Alternate Quoting Syntax:
- Using Here Documents:
Contact Us