Ruby Strings
Working with text data in Ruby
📝 What are Ruby Strings?
Strings are sequences of characters used to represent text. Ruby provides powerful string manipulation methods. You can create strings using single or double quotes, with double quotes supporting interpolation and escape sequences.
# Creating strings
name = "Alice"
greeting = 'Hello'
message = "Welcome, #{name}!" # Interpolation
puts message # Output: Welcome, Alice!
String Operations
Concatenation
Join strings together
"Hello" + " World"
# "Hello World"
Searching
Find text within strings
"Hello".include?("ell")
# true
Slicing
Extract parts of strings
"Hello"[0..2]
# "Hel"
Transformation
Modify string content
"hello".upcase
# "HELLO"
🔹 Creating Strings
Ruby offers multiple ways to create strings. Single quotes create literal strings, while double quotes allow interpolation and escape sequences.
# Single quotes (literal)
str1 = 'Hello World'
puts str1 # Output: Hello World
# Double quotes (with interpolation)
name = "Alice"
str2 = "Hello, #{name}!"
puts str2 # Output: Hello, Alice!
# Multi-line strings
str3 = "Line 1\nLine 2\nLine 3"
puts str3
# Output:
# Line 1
# Line 2
# Line 3
Output:
Hello World Hello, Alice! Line 1 Line 2 Line 3
🔹 String Interpolation
String interpolation embeds expressions inside strings using #{}. It only works with double quotes and evaluates the expression inside.
# Basic interpolation
age = 25
puts "I am #{age} years old" # Output: I am 25 years old
# Expression interpolation
x = 10
y = 5
puts "Sum: #{x + y}" # Output: Sum: 15
# Method interpolation
name = "alice"
puts "Hello, #{name.capitalize}!" # Output: Hello, Alice!
Output:
I am 25 years old Sum: 15 Hello, Alice!
🔹 String Concatenation
Combine strings using the + operator or << operator. The + creates a new string, while << modifies the original.
# Using + operator
first = "Hello"
last = "World"
result = first + " " + last
puts result # Output: Hello World
# Using << operator
greeting = "Hello"
greeting << " World"
puts greeting # Output: Hello World
# Using concat method
str = "Ruby"
str.concat(" Programming")
puts str # Output: Ruby Programming
Output:
Hello World Hello World Ruby Programming
🔹 String Methods
Ruby provides many built-in methods to manipulate strings. These methods make text processing easy and efficient.
text = " Hello World "
# Length
puts text.length # Output: 15
# Case conversion
puts text.upcase # Output: HELLO WORLD
puts text.downcase # Output: hello world
puts text.capitalize # Output: hello world
# Trimming whitespace
puts text.strip # Output: Hello World
puts text.lstrip # Output: Hello World
puts text.rstrip # Output: Hello World
Output:
15 HELLO WORLD hello world hello world Hello World Hello World Hello World
🔹 String Searching
Search for substrings using various methods. Ruby provides flexible ways to check if text contains specific patterns.
text = "Hello Ruby World"
# Check if string includes substring
puts text.include?("Ruby") # Output: true
puts text.include?("Python") # Output: false
# Find index of substring
puts text.index("Ruby") # Output: 6
puts text.index("Python") # Output: nil
# Check start and end
puts text.start_with?("Hello") # Output: true
puts text.end_with?("World") # Output: true
Output:
true false 6 nil true true
🔹 String Slicing
Extract portions of strings using bracket notation or slice methods. You can access individual characters or ranges.
text = "Hello World"
# Single character
puts text[0] # Output: H
puts text[-1] # Output: d (last character)
# Range of characters
puts text[0..4] # Output: Hello
puts text[6..-1] # Output: World
# Using slice method
puts text.slice(0, 5) # Output: Hello
puts text.slice(6, 5) # Output: World
Output:
H d Hello World Hello World
🔹 String Replacement
Replace parts of strings using gsub (global substitution) or sub (single substitution) methods.
text = "Hello World, Hello Ruby"
# Replace first occurrence
puts text.sub("Hello", "Hi")
# Output: Hi World, Hello Ruby
# Replace all occurrences
puts text.gsub("Hello", "Hi")
# Output: Hi World, Hi Ruby
# Remove characters
puts text.gsub("Hello ", "")
# Output: World, Ruby
Output:
Hi World, Hello Ruby Hi World, Hi Ruby World, Ruby
🔹 String Splitting and Joining
Split strings into arrays or join arrays into strings. These operations are useful for parsing and formatting text.
# Splitting strings
text = "apple,banana,orange"
fruits = text.split(",")
puts fruits.inspect # Output: ["apple", "banana", "orange"]
# Splitting by space
sentence = "Hello Ruby World"
words = sentence.split(" ")
puts words.inspect # Output: ["Hello", "Ruby", "World"]
# Joining arrays
arr = ["Ruby", "is", "awesome"]
result = arr.join(" ")
puts result # Output: Ruby is awesome
Output:
["apple", "banana", "orange"] ["Hello", "Ruby", "World"] Ruby is awesome
💡 Common String Methods:
- length/size: Get string length
- upcase/downcase: Change case
- strip/lstrip/rstrip: Remove whitespace
- include?: Check if substring exists
- split: Convert string to array
- gsub/sub: Replace text
- reverse: Reverse string order
- chars: Convert to character array