String
String.new, String() Returns:
String · Updated March 13, 2026 · Kernel Methods strings text characters encoding
The String class is fundamental to Ruby, representing sequences of characters. Ruby’s strings are versatile, mutable, and natively support UTF-8 encoding.
Creating Strings
# Literals
"hello" # => "hello"
'hello' # => "hello" (no interpolation)
%q{hello} # => "hello"
%Q{hello #{world}} # => "hello world"
# Constructor
String.new("hello") # => "hello"
String(42) # => "42"
String Methods
Querying
"hello".length # => 5
"hello".size # => 5
"hello".empty? # => false
"".empty? # => true
"hello".bytesize # => 5 (UTF-8 bytes)
Modification
# Concatenation
"hello" + " world" # => "hello world"
"hello" << " world" # => "hello world" (mutating)
"hello" * 3 # => "hellohellohello"
Case Conversion
"HELLO".downcase # => "hello"
"hello".upcase # => "HELLO"
"Hello".capitalize # => "Hello"
"HeLLo".swapcase # => "hEllO"
Searching and Replacing
"hello".include?("ll") # => true
"hello".index("ll") # => 2
"hello".start_with?("he") # => true
"hello".end_with?("lo") # => true
"hello".gsub("l", "r") # => "herro"
Encoding
# Default UTF-8
"hello".encoding # => #<Encoding:UTF-8>
# Convert encoding
"hello".encode("ASCII") # => "hello"
"héllo".encode("ASCII", invalid: :replace) # => "?ll?"
Practical Examples
Splitting and Joining
"a,b,c".split(",") # => ["a", "b", "c"]
["a", "b", "c"].join("-") # => "a-b-c"
Stripping Whitespace
" hello ".strip # => "hello"
"hello\n".chomp # => "hello"
Interpolation
name = "World"
"Hello, #{name}!" # => "Hello, World!"
Multiline Strings
# Heredoc
text = <<~TEXT
This is a multiline
string in Ruby
TEXT
# % notation
text = <<-TEXT
Indented heredoc
TEXT
Mutable Strings
Unlike some languages, Ruby strings are mutable:
str = "hello"
str << " world" # Mutates: "hello world"
str.upcase! # Mutates: "HELLO"
String Encoding Issues
# Force encoding
str = "hello".force_encoding("UTF-8")
# Valid encoding check
"hello".valid_encoding? # => true
The String class provides extensive functionality for text processing, making Ruby excellent for tasks involving string manipulation.