Home
Ruby
String Literal Examples
Updated Sep 15, 2023
Dot Net Perls
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' puts result result = "bird" puts result
bird 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 value1 puts value2 puts value3
This 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 test
What 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.
Method
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen