String
literalsA 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.
Simple string
literals can be contained in quotes. More complex literals can begin with the percentage sign, and continue for multiple lines.
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' puts result result = "bird" puts resultbird bird
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.
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 value1 puts value2 puts value3This is "ruby" string This is also 'one' This is another "string"
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...?
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
.