Strings
## Learning Objectives
- Create and manipulate strings
- Master string interpolation
- Use string methods effectively
- Format strings with various techniques
## Creating Strings
### Single Quotes
```ruby
# Literal - no interpolation
name = 'Alice'
greeting = 'Hello, #{name}' # No interpolation!
puts greeting # "Hello, #{name}"
# Escape characters
path = 'C:\\Users\\Alice\\Documents'
puts path # "C:\Users\Alice\Documents"
```
### Double Quotes
```ruby
# Interpolation allowed
name = "Alice"
greeting = "Hello, #{name}"
puts greeting # "Hello, Alice"
# Expression interpolation
puts "2 + 2 = #{2 + 2}" # "2 + 2 = 4"
```
### Other Syntaxes
```ruby
# Here document (multi-line)
poem = <<~TEXT
Roses are red,
Violets are blue,
Ruby is fun,
And so are you.
TEXT
# Percent notation
array_string = %w(apple banana cherry) # Array
interpolated = %W(Hello #{name}) # Array with interpolation
single_quoted = %q(Hello world) # Single-quoted string
double_quoted = %Q(Hello #{name}) # Double-quoted string
```
## String Interpolation
```ruby
name = "Ruby"
version = 3.0
puts "Welcome to #{name} #{version}!"
puts "Sum: #{1 + 2}"
puts "Uppercase: #{name.upcase}"
puts "Length: #{name.length}"
```
## Escape Sequences
| Sequence | Meaning |
|----------|---------|
| `\n` | Newline |
| `\t` | Tab |
| `\r` | Carriage return |
| `\\` | Backslash |
| `\"` | Double quote |
| `\'` | Single quote |
| `\b` | Backspace |
| `\s` | Space |
## String Methods
### Querying
```ruby
str = "Hello, World!"
str.length # 13
str.size # 13
str.empty? # false
str.include?("World") # true
str.start_with?("Hello") # true
str.end_with?("!") # true
str.index("World") # 7
str.rindex("o") # 8
str.count("l") # 3
```
### Case Conversion
```ruby
"hello".upcase # "HELLO"
"HELLO".downcase # "hello"
"hello".capitalize # "Hello"
"hELLO".swapcase # "HellO"
```
### Stripping Whitespace
```ruby
" hello ".strip # "hello"
" hello".lstrip # "hello "
"hello ".rstrip # " hello"
"hello".strip.empty? # false
```
### Splitting and Joining
```ruby
"one,two,three".split(",") # ["one", "two", "three"]
"hello world".split # ["hello", "world"]
"hello".chars # ["h", "e", "l", "l", "o"]
"hello".each_char.to_a # ["h", "e", "l", "l", "o"]
"one,two,three".split(",", 2) # ["one", "two,three"]
["hello", "world"].join(" ") # "hello world"
["a", "b", "c"].join # "abc"
```
### Substrings
```ruby
str = "Hello, World!"
str[0] # "H"
str[0, 5] # "Hello" (start, length)
str[0..4] # "Hello" (inclusive range)
str[7..11] # "World"
str[-1] # "!"
str[0..-2] # "Hello, World" (everything but last)
str.slice(0) # "H"
str.slice(0, 5) # "Hello"
str.slice(0..4) # "Hello"
```
### Replacing
```ruby
"hello".replace("world") # "world" (mutates)
"hello".sub("l", "x") # "hexlo" (first only)
"hello".gsub("l", "x") # "hexxo" (all)
"hello".gsub(/[aeiou]/, "*") # "h*ll*" (regex)
# With captures
"hello".gsub(/(.)(.)/) { |a, b| b + a } # "ehllo"
```
### Inserting and Deleting
```ruby
"hello".insert(1, " World") # "h Worldello"
"hello" << " World" # "hello World" (shovel)
"hello".concat(" World") # "hello World"
"hello".prepend("say: ") # "say: hello"
"hello".concat(" world") # "hello world"
"hello".delete("l") # "heo"
```
### Searching and Matching
```ruby
"hello".index("l") # 2
"hello".rindex("l") # 3
"hello".match(/[aeiou]/) # #
"hello" =~ /[aeiou]/ # 1 (index or nil)
"hello" =~ /x/ # nil
"hello".match?(/[aeiou]/) # true (Ruby 2.4+)
```
### Formatting
```ruby
# String formatting
name = "Alice"
age = 30
# sprintf style
sprintf("Name: %s, Age: %d", name, age) # "Name: Alice, Age: 30"
format("PI: %.2f", 3.14159) # "PI: 3.14"
# % operator
"Name: %s, Age: %d" % [name, age] # "Name: Alice, Age: 30"
```
### Padding and Alignment
```ruby
"hello".ljust(10) # "hello "
"hello".rjust(10) # " hello"
"hello".center(10) # " hello "
"hello".ljust(10, "-") # "hello-----"
"hello".center(11, "=") # "==hello==="
```
### Other Useful Methods
```ruby
"hello".reverse # "olleh"
"hello".succ # "iellp" (next string)
"hello".next # "iellp" (alias)
"hello".ord # 104 (character code)
"h".ord # 104
104.chr # "h"
"abc".crypt("xx") # Encrypted (obsolete, use securerandom)
# Encoding
"hello".encoding # #
"hello".encode("UTF-16LE") # Convert encoding
```
## Regular Expressions with Strings
```ruby
# Match
"hello 123"[/[0-9]+/] # "123"
"hello"[/[0-9]+/] # nil
# Scan (all matches)
"hello 123 world 456"[/\d+/] # "123"
"hello 123 world 456".scan(/\d+/) # ["123", "456"]
# Split with regex
"one,two,three".split(/,/) # ["one", "two", "three"]
"a1b2c3".split(/[0-9]/) # ["a", "b", "c", ""]
```
## Mutating Methods
Most string methods return new strings. Some mutate in place:
```ruby
str = "hello"
# Non-mutating (returns new string)
str.upcase # "HELLO"
str # "hello" (unchanged)
# Mutating (with !)
str.upcase! # "HELLO"
str # "HELLO" (changed)
```
### Mutating Methods List
| Method | Mutates? | Returns |
|--------|----------|---------|
| `upcase` | No | New string |
| `upcase!` | Yes | `self` or `nil` |
| `replace` | Yes | `self` |
| `concat` | Yes | `self` |
| `prepend` | Yes | `self` |
| `insert` | Yes | `self` |
| `clear` | Yes | `self` |
## Summary
- Double quotes allow interpolation, single quotes are literal
- `#{expression}` for interpolation
- `%Q()`, `%W()`, `%q()`, `%w()` for special string creation
- `strip`, `lstrip`, `rstrip` for whitespace
- `split`, `join` for array conversion
- `sub` (first) and `gsub` (all) for replacement
- `[]` for substring access
- Mutating methods end with `!` (or return new string)
- Regular expressions: `/pattern/`, `=~`, `match`, `scan`
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →