How to Create String in Ruby: Syntax and Examples
In Ruby, you create a string by enclosing text within
"double quotes" or 'single quotes'. You can also use %q() or %Q() for alternative string creation methods.Syntax
Ruby strings can be created using different ways:
- Double quotes: Allows string interpolation and escape sequences.
- Single quotes: Treats content literally, no interpolation.
- %q(): Creates a single-quoted string (no interpolation).
- %Q(): Creates a double-quoted string (supports interpolation).
ruby
str1 = "Hello, world!" str2 = 'Hello, world!' str3 = %q(Hello, world!) str4 = %Q(Hello, #{"world"}!)
Example
This example shows how to create strings using different methods and how interpolation works with double quotes and %Q().
ruby
name = "Alice" str1 = "Hello, #{name}!" str2 = 'Hello, #{name}!' str3 = %q(Hello, #{name}!) str4 = %Q(Hello, #{name}!) puts str1 puts str2 puts str3 puts str4
Output
Hello, Alice!
Hello, #{name}!
Hello, #{name}!
Hello, Alice!
Common Pitfalls
One common mistake is expecting string interpolation to work inside single quotes or %q() strings, but it does not. Also, forgetting to close quotes properly causes syntax errors.
ruby
name = "Bob" # Wrong: no interpolation in single quotes str_wrong = 'Hello, #{name}!' # Right: interpolation works in double quotes str_right = "Hello, #{name}!" puts str_wrong puts str_right
Output
Hello, #{name}!
Hello, Bob!
Quick Reference
| Syntax | Description |
|---|---|
| "text" | Double-quoted string with interpolation and escapes |
| 'text' | Single-quoted string, literal content |
| %q(text) | Single-quoted style string, no interpolation |
| %Q(text) | Double-quoted style string, supports interpolation |
Key Takeaways
Use double quotes or %Q() for strings when you need interpolation or escape sequences.
Single quotes and %q() create literal strings without interpolation.
Always close your quotes properly to avoid syntax errors.
String interpolation only works inside double-quoted or %Q() strings.
Ruby offers flexible syntax options to create strings based on your needs.