String#force_encoding changes how Ruby interprets a string's bytes without altering them, fixing encoding labels on text from files, sockets, and databases.
Reference
String Methods
Methods available on Ruby String objects.
- force_encoding
- String#bytes
Returns an array of integers representing the raw byte values of a string. Encoding-aware and essential for binary data work.
- String#bytesize
Returns the number of bytes used by a string's encoding, which can differ from character count for multibyte text and emoji.
- String#byteslice
Extracts a substring by byte index. Unlike slice, byteslice works with byte positions instead of character positions.
- String#capitalize
Return a copy of a string with the first character uppercased and the rest lowercased for display-friendly text and simple cleanup.
- String#center
Use String#center to pad strings to a specified width with centered text in Ruby. Create aligned headings and formatted tables for terminal output.
- String#chars
String#chars breaks a Ruby string into an array of characters for easy iteration, counting, and transformation. Supports Unicode and multi-byte characters.
- String#chomp
Removes the trailing record separator (newline, carriage return) from a string. Returns a new string with the separator removed.
- String#chomp
Remove trailing line separators from a string, including CR, LF, and CRLF endings, plus custom separators and the special nil or empty separator cases.
- String#chop
String#chop returns a new string with the last character removed, useful for path cleanup, input processing, and removing trailing delimiters.
- String#chop
String#chop removes the last character from a Ruby string, or the final CRLF pair. Unlike chomp, it removes any trailing character unconditionally.
- String#chop!
Remove the last character from a string in place with String#chop!, returning the modified string or nil when the text is empty.
- String#clone
Create a shallow copy of a string in Ruby, preserving frozen status and singleton methods when you need a copy that behaves like the original.
- String#concat
Concatenates one or more strings onto the original string in Ruby. The + operator is an alias, and concat can also accept multiple arguments at once.
- String#count
Counts the number of occurrences of each character or substring in a string. Returns an integer representing the total count.
- String#crypt
String#crypt encrypts a string with POSIX crypt(3) and a salt. Deprecated since Ruby 2.5, use the string-crypt gem instead. Safer than legacy DES for hashing.
- String#delete
Removes characters from a string. Pass one or more character sets to delete; returns a new string with all matching characters removed.
- String#downcase
String#downcase returns a lowercase copy of the string without changing the original. Useful for case-insensitive comparisons and normalizing user input.
- String#downcase
String#downcase converts a string to lowercase with Unicode-aware case mapping, supporting Turkish, Lithuanian, and ASCII-only modes for precise normalization.
- String#dup
String#dup returns a shallow, unfrozen copy of a String. Use the string-dup method for defensive copying and unfreezing frozen string literals.
- String#each_char
Iterate over each character or line in a Ruby string. each_char yields single characters while each_line splits by line separators.
- String#each_line
Use String#each_line in Ruby to iterate over each line of a string or IO object. Split by custom separators and process line-by-line efficiently.
- String#empty?
Check if a Ruby string has zero length with the empty? method. Returns true for empty strings and false otherwise, handling nil via safe navigation.
- String#encode
Converts the encoding of a string to the specified encoding, returning a new string with the characters re-encoded.
- String#encoding
Use String#encoding in Ruby to inspect and manage string encoding. Learn how to check, transcode, and validate character encodings for text data.
- String#end_with?
Checks whether a string ends with one or more suffixes, which is useful for file extensions, route guards, and other simple validation rules.
- String#end_with?
Checks whether a string ends with one suffix or several suffixes, which is useful for file extensions, URL checks, and routing rules.
- String#freeze
String#freeze locks a string against modification, marking it immutable so that any later change raises a FrozenError and the value stays stable.
- String#gsub
Replace all occurrences of a pattern in a string. Works with strings, regexes, hashes, and blocks. Returns a new string.
- String#gsub!
Use String#gsub! for in-place global substitution in Ruby, replacing every matching pattern with a new value or block result and returning nil when unchanged.
- String#hex
Converts the leading hex substring of a string to an integer, accepting an optional 0x prefix and stopping cleanly at the first non-hex character it encounters.
- String#include?
String#include? checks if a substring exists inside a string, returning a boolean for quick checks, file extension tests, and validation rules in Ruby.
- String#include?
Use String#include? to check if a string contains a substring in Ruby, returning a boolean for input validation, file type detection, and guard clauses.
- String#index
Finds the position of a substring within a string. index searches from the left, rindex searches from the right.
- String#insert
Use String#insert to place a substring at any index, with negative-index support. Covers edge cases, error handling, and how it compares to other methods.
- String#length
String#length returns the character count of a Ruby string in O(1) time, making it the go-to tool for input validation, truncation, and display limits.
- String#lines — Split Lines Into an Array
How to split string lines in Ruby using String#lines. Covers chomp, custom separators, paragraph mode, line ending handling, and gotchas.
- String#ljust
Pad a string to a specified width on the right with the given filler, left-justifying the original string for tables, logs, and fixed-width output.
- String#lstrip
Removes leading and/or trailing whitespace from a string. lstrip removes left (leading), rstrip removes right (trailing), strip removes both.
- String#match
Match a Ruby string against a regex pattern with String#match, returning MatchData with captures and positions or nil. Use match? for faster boolean checks.
- String#match
Search a string for a pattern and return MatchData, or nil if no match is found, using a regexp, string pattern, or optional start position.
- String#match?
The match? method checks if a regex matches a Ruby string without allocating MatchData, making it the lighter choice for validation, guards, and conditionals.
- String#next
Use String#next (aliased as succ) to step through alphanumeric sequences in Ruby, with automatic carry between character classes and controlled padding.
- String#oct
Converts a string to an integer by reading leading characters as octal, with support for 0b and 0x prefixes, negative numbers, and early stop rules.
- String#partition
Divides a string into three parts at a separator and returns [before, separator, after] as a 3-element array for easy parsing.
- String#prepend
Prepends one or more strings to the beginning of a string in place, returning the modified string itself so you can keep working with the same object.
- String#replace
Ruby's String#replace swaps a string's contents in place while keeping the same object. When mutation beats reassignment for buffers and shared references.
- String#replace
Replace a string's contents in place with another string. Unlike sub or gsub, String#replace swaps the entire content while keeping the same object identity.
- String#reverse
Return a new string with the characters in reverse order for palindrome checks, text transforms, and quick text cleanup.
- String#reverse
Reverse a string in Ruby with the reverse method. Also covers reverse! for in-place reversal and use cases like palindrome checks.
- String#rindex
String#rindex searches from the right, returning the index of the last occurrence of a substring or regex, ideal for file extensions and path separators.
- String#rjust
Use String#rjust to pad a string on the left to a fixed width in Ruby, right-justifying text for tables, numeric columns, and terminal formatting.
- String#rstrip
Ruby String#rstrip removes trailing whitespace (spaces, tabs, newlines) from the right side of a string, returning a clean copy without modifying the original.
- String#scan
Use the String#scan method to find all pattern matches in a string and return them as an array, with support for regex capturing groups and block iteration.
- String#scan
Find all occurrences of a pattern in a string, returning an array of matches. Use a block to process each match without building an intermediate array.
- String#slice
String#slice extracts a substring by index, range, or regular expression and returns nil when not found. Works with indexing, ranges, and capture groups.
- String#split
Split a string into parts with a delimiter or regex, then control the result with an optional limit when parsing text, logs, or CSV-like data in Ruby.
- String#split with Delimiters and Limits
Split a string into an array of substrings by a delimiter. Supports regex patterns, limits, and special empty-string handling.
- String#squeeze
Returns a new string with consecutive repeated characters collapsed to a single character. Optionally squeeze specific characters only.
- String#start_with?
String#start_with? checks whether a string begins with a given prefix or any of several prefixes, useful for validation, routing, and simple parsing.
- String#strip
Removes leading and trailing whitespace from strings, ideal for cleaning user input, parsing CSV data, and normalizing values from files or forms in Ruby.
- String#strip for Leading and Trailing Whitespace
Remove leading and trailing whitespace from a string. Also removes null bytes, form feeds, and tabs. Use lstrip or rstrip to remove from one side only.
- String#sub
Replaces the first occurrence of a pattern in a string. Returns a new string with only the first match replaced.
- String#sub with Regex and Block Forms
Replace the first occurrence of a pattern in a Ruby string. Use a string, regexp, or block to compute the replacement while leaving the original unchanged.
- String#succ
Returns the next lexicographic string after the current one, incrementing characters from right to left with carry propagation.
- String#swapcase
The swapcase method returns a copy of the string with uppercase characters converted to lowercase and lowercase characters converted to uppercase.
- String#swapcase with Unicode Options
Returns a new string with the case of each character swapped in Ruby, turning uppercase letters into lowercase and lowercase letters into uppercase.
- String#to_i
Convert a string to an integer with to_i, optionally using a base from 2 to 36, and understand how malformed input falls back to zero.
- String#to_sym
Converts a string to a symbol. Returns the symbol corresponding to the string content, or creates a new symbol if it doesn't already exist.
- String#tr
Replaces characters in a string according to a mapping from from_str to to_str, making simple character translation fast and predictable.
- String#unicode_normalize
Normalize Unicode strings to a consistent form (NFC, NFD, NFKC, NFKD) for reliable comparison and storage in Ruby.
- String#unpack
Decodes a binary string according to a template format, returning an array of values (or a single value for unpack1).
- String#unpack1
Returns the first element of a packed string interpretation, converting binary data to Ruby values when you only need one decoded value.
- String#upcase
String#upcase converts all characters in a string to uppercase in Ruby, preserving the original. Useful for normalizing input and formatting display labels.
- String#upcase with Unicode Options
Convert a Ruby string to uppercase using Unicode-aware case mapping for display formatting, normalization, and case-insensitive comparisons.
- String#valid_encoding?
String#valid_encoding? checks whether a string's bytes form a valid sequence for its current encoding. Learn how to detect and handle invalid UTF-8 data.