rubyguides

Reference

String Methods

Methods available on Ruby String objects.

  1. force_encoding

    String#force_encoding changes how Ruby interprets a string's bytes without altering them, fixing encoding labels on text from files, sockets, and databases.

  2. String#bytes

    Returns an array of integers representing the raw byte values of a string. Encoding-aware and essential for binary data work.

  3. String#bytesize

    Returns the number of bytes used by a string's encoding, which can differ from character count for multibyte text and emoji.

  4. String#byteslice

    Extracts a substring by byte index. Unlike slice, byteslice works with byte positions instead of character positions.

  5. String#capitalize

    Return a copy of a string with the first character uppercased and the rest lowercased for display-friendly text and simple cleanup.

  6. 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.

  7. 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.

  8. String#chomp

    Removes the trailing record separator (newline, carriage return) from a string. Returns a new string with the separator removed.

  9. 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.

  10. String#chop

    String#chop returns a new string with the last character removed, useful for path cleanup, input processing, and removing trailing delimiters.

  11. 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.

  12. 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.

  13. 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.

  14. 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.

  15. String#count

    Counts the number of occurrences of each character or substring in a string. Returns an integer representing the total count.

  16. 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.

  17. String#delete

    Removes characters from a string. Pass one or more character sets to delete; returns a new string with all matching characters removed.

  18. String#downcase

    String#downcase returns a lowercase copy of the string without changing the original. Useful for case-insensitive comparisons and normalizing user input.

  19. String#downcase

    String#downcase converts a string to lowercase with Unicode-aware case mapping, supporting Turkish, Lithuanian, and ASCII-only modes for precise normalization.

  20. 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.

  21. 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.

  22. 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.

  23. 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.

  24. String#encode

    Converts the encoding of a string to the specified encoding, returning a new string with the characters re-encoded.

  25. 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.

  26. 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.

  27. 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.

  28. 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.

  29. String#gsub

    Replace all occurrences of a pattern in a string. Works with strings, regexes, hashes, and blocks. Returns a new string.

  30. 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.

  31. 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.

  32. 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.

  33. 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.

  34. String#index

    Finds the position of a substring within a string. index searches from the left, rindex searches from the right.

  35. 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.

  36. 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.

  37. 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.

  38. 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.

  39. String#lstrip

    Removes leading and/or trailing whitespace from a string. lstrip removes left (leading), rstrip removes right (trailing), strip removes both.

  40. 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.

  41. 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.

  42. 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.

  43. String#next

    Use String#next (aliased as succ) to step through alphanumeric sequences in Ruby, with automatic carry between character classes and controlled padding.

  44. 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.

  45. String#partition

    Divides a string into three parts at a separator and returns [before, separator, after] as a 3-element array for easy parsing.

  46. 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.

  47. 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.

  48. 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.

  49. String#reverse

    Return a new string with the characters in reverse order for palindrome checks, text transforms, and quick text cleanup.

  50. String#reverse

    Reverse a string in Ruby with the reverse method. Also covers reverse! for in-place reversal and use cases like palindrome checks.

  51. 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.

  52. 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.

  53. 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.

  54. 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.

  55. 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.

  56. 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.

  57. 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.

  58. 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.

  59. String#squeeze

    Returns a new string with consecutive repeated characters collapsed to a single character. Optionally squeeze specific characters only.

  60. 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.

  61. 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.

  62. 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.

  63. String#sub

    Replaces the first occurrence of a pattern in a string. Returns a new string with only the first match replaced.

  64. 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.

  65. String#succ

    Returns the next lexicographic string after the current one, incrementing characters from right to left with carry propagation.

  66. String#swapcase

    The swapcase method returns a copy of the string with uppercase characters converted to lowercase and lowercase characters converted to uppercase.

  67. 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.

  68. 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.

  69. 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.

  70. String#tr

    Replaces characters in a string according to a mapping from from_str to to_str, making simple character translation fast and predictable.

  71. String#unicode_normalize

    Normalize Unicode strings to a consistent form (NFC, NFD, NFKC, NFKD) for reliable comparison and storage in Ruby.

  72. String#unpack

    Decodes a binary string according to a template format, returning an array of values (or a single value for unpack1).

  73. String#unpack1

    Returns the first element of a packed string interpretation, converting binary data to Ruby values when you only need one decoded value.

  74. 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.

  75. String#upcase with Unicode Options

    Convert a Ruby string to uppercase using Unicode-aware case mapping for display formatting, normalization, and case-insensitive comparisons.

  76. 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.