String literals. A string literal is string data directly specified in a program. In Ruby, we use the single-quote, or double-quote character to create string literals.
Syntax notes. Simple string literals can be contained in quotes. More complex literals can begin with the percentage sign, and continue for multiple lines.
Simple literals. We can use single or double quotes in Ruby programs to enclose string literals. The choice mostly depends on what syntax you prefer.
# Use single and double quotes.
result = 'bird'
result = "bird"
Complex example. We use the percent "%" character at the start of 2 literals. In this form, we can use another character, such as a vertical bar or "+" as a delimiter.
Tip With this syntax form, we can place double-quotes in a string literal without escaping it.
# String literals.
value1 = %|This is "ruby" string|
value2 = %+This is also 'one'+
value3 = "This is another \"string\""
# Display results.
puts value3This is "ruby" string
This is also 'one'
This is another "string"
Line break. With delimiter characters containing a string literal, we can enclose a newline char. This helps with multi-line string data.
# String literal with line break.
test = %|What about
the time you said...?|
puts testWhat about
the time you said...?
A summary. String literals are used in most Ruby programs. They can be passed as arguments, or used in assignments to local variables. They can be used like any other string.