Home » Tutorial: Strings in Ruby

Tutorial: Strings in Ruby

Strings in Ruby are sequences of characters enclosed in single or double quotes.

They are one of the most commonly used data types, supporting various operations like concatenation, interpolation, and modification.

What You’ll Learn

1. Introduction to Strings

A string in Ruby can represent text, numbers, or special characters. Strings are mutable, meaning their contents can be modified.

2. Creating Strings

Using Single Quotes

Single-quoted strings are simple but do not support interpolation or most escape sequences.

single_quote = 'Hello, Ruby!'
puts single_quote  # Output: Hello, Ruby!

Using Double Quotes

Double-quoted strings support interpolation and escape sequences.

double_quote = "Hello, Ruby!"
puts double_quote  # Output: Hello, Ruby!

Using %q and %Q

  • %q is similar to single quotes.
  • %Q is similar to double quotes.
string1 = %q(This is a single-quoted string)
string2 = %Q(This is a "double-quoted" string)
puts string1  # Output: This is a single-quoted string
puts string2  # Output: This is a "double-quoted" string

Using Here-Document (Heredoc)

Heredoc allows multi-line strings.

multi_line_string = <<~HEREDOC
  This is a multi-line string.
  You can add as many lines as you want.
HEREDOC
puts multi_line_string

3. String Operations

Concatenation

str1 = "Hello, "
str2 = "World!"
result = str1 + str2
puts result  # Output: Hello, World!

Appending

str = "Hello"
str << ", Ruby!"
puts str  # Output: Hello, Ruby!

Multiplication

str = "Ruby! " * 3
puts str  # Output: Ruby! Ruby! Ruby!

4. String Interpolation

Interpolation embeds variables or expressions into a string using #{}. Only works with double-quoted strings or %Q.

Example

name = "Alice"
greeting = "Hello, #{name}!"
puts greeting  # Output: Hello, Alice!

Expression Interpolation

number = 10
puts "The square of #{number} is #{number ** 2}."  # Output: The square of 10 is 100.

5. Escape Characters

Escape characters allow special characters to be included in a string.

Escape Sequence Description
\n Newline
\t Tab
\” Double quote
\’ Single quote
\\ Backslash

Example

puts "Line 1\nLine 2"  # Output:
# Line 1
# Line 2

puts "She said, \"Hello!\""  # Output: She said, "Hello!"

6. String Methods

6.1 Length and Size

str = "Hello, Ruby!"
puts str.length  # Output: 12
puts str.size    # Output: 12

6.2 Case Conversion

str = "Ruby Programming"
puts str.upcase   # Output: RUBY PROGRAMMING
puts str.downcase # Output: ruby programming
puts str.capitalize # Output: Ruby programming
puts str.swapcase # Output: rUBY pROGRAMMING

6.3 Check for Inclusion

str = "Hello, Ruby!"
puts str.include?("Ruby")  # Output: true
puts str.start_with?("Hello") # Output: true
puts str.end_with?("!")   # Output: true

6.4 Substring Extraction

str = "Hello, Ruby!"
puts str[0]     # Output: H
puts str[0, 5]  # Output: Hello
puts str[-1]    # Output: !

6.5 Replace and Modify

str = "Hello, Ruby!"
puts str.sub("Ruby", "World")  # Output: Hello, World!
puts str.gsub("l", "L")        # Output: HeLLo, Ruby!

6.6 Splitting and Joining

str = "Hello Ruby World"
words = str.split(" ")
puts words.inspect  # Output: ["Hello", "Ruby", "World"]

joined = words.join("-")
puts joined  # Output: Hello-Ruby-World

6.7 Strip and Trim

str = "   Hello, Ruby!   "
puts str.strip  # Output: Hello, Ruby!
puts str.lstrip # Output: Hello, Ruby!   
puts str.rstrip # Output:    Hello, Ruby!

6.8 Reverse a String

str = "Ruby"
puts str.reverse  # Output: ybuR

6.9 String Iteration

str = "Ruby"
str.each_char { |char| puts char }
# Output:
# R
# u
# b
# y

7. Practical Examples

7.1 Create a Greeting Message

name = "Alice"
puts "Welcome, #{name}!"  # Output: Welcome, Alice!

7.2 Check if a String Is Palindrome

def palindrome?(str)
  str.downcase == str.downcase.reverse
end

puts palindrome?("Racecar")  # Output: true
puts palindrome?("Hello")    # Output: false

7.3 Count Vowels in a String

def count_vowels(str)
  str.count("aeiouAEIOU")
end

puts count_vowels("Hello, Ruby!")  # Output: 4

7.4 Replace Words in a Sentence

sentence = "I love programming in Ruby."
puts sentence.gsub("Ruby", "Python")  # Output: I love programming in Python.

7.5 Format a Multiline String

text = <<~TEXT
  Ruby is:
  - Easy to learn
  - Fun to use
  - Powerful
TEXT

puts text
# Output:
# Ruby is:
# - Easy to learn
# - Fun to use
# - Powerful

8. Summary

Key Points

  • Ruby strings can be created using single quotes, double quotes, heredocs, and %q/%Q.
  • String interpolation works only with double quotes or %Q.
  • Ruby provides powerful built-in methods for string manipulation.

Best Practices

  1. Use string interpolation instead of concatenation for cleaner code.
  2. Avoid excessive mutation of strings; use immutable methods like gsub over sub! unless necessary.
  3. Take advantage of Ruby’s expressive methods to simplify string operations.

You may also like