Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 134 · Getting Started

String Methods

A practical tour of Ruby string methods - length, case, strip, split, sub and gsub, slicing, padding, searching, chars, each_line and encoding basics, with examples.

Ruby's String class has well over a hundred methods. You do not need to memorize them, but you should know the dozen or so that appear in almost every program, and the naming patterns that make the rest guessable. This lesson walks through the everyday ones in groups: measuring and changing case, trimming, splitting and joining, searching and replacing, slicing, padding and formatting, and a first look at encodings.

Two conventions help you read any Ruby code. A method ending in ? returns true or false (empty?, start_with?). A method ending in ! is the in-place version of a method of the same name: upcase returns a new string, upcase! changes the original and returns nil if nothing changed. If you have not read Strings yet, skim it first, because mutation is the main pitfall.

Size, case and emptiness

Ruby Length, case and tests

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

length and size are the same. include?, start_with? and end_with? take plain strings (and start_with? also accepts a regex). count takes a set of characters, not a substring: "hello".count("el") counts every e and every l. index returns a zero-based position or nil when nothing matches, which is why you should not do arithmetic on it without checking.

Trimming and cleaning

User input and file lines usually arrive with stray whitespace or a trailing newline.

Ruby strip, chomp and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

strip removes whitespace (spaces, tabs, newlines) from both ends. chomp is narrower: it removes a single trailing line ending, which is exactly what you want after gets. delete_prefix and delete_suffix are the clean way to cut a known beginning or end; they do nothing if the text is not there.

Splitting and joining

Ruby split and join

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

split with no argument is the best way to get words: it ignores leading whitespace and treats runs of spaces, tabs and newlines as one separator. With a string argument it keeps empty pieces in the middle but drops empty ones at the end unless you pass a negative limit. A positive limit caps the number of pieces, which is how you split key=value at the first equals sign only. join is a method of Array, but it is the other half of split.

Searching and replacing

sub replaces the first match and gsub replaces every match. The pattern can be a string or a regular expression (Regular Expressions covers regexes properly).

Ruby sub, gsub, tr and scan

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

When the replacement needs logic, pass a block: it receives the matched text and its result is inserted. With a hash, each match is looked up in the hash. Prefer match? when you only need a yes or no: it is faster because it does not build a match object. And remember the last line: bang methods return nil when they changed nothing, so never chain them as s.sub!(...).upcase.

Replacement strings and backslashes

In a replacement string, \1 refers to the first capture group. Because the backslash is also a string escape, write "\\1" or use a block:

Ruby Capture groups in replacements

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Single quotes make this easier to read, because '\3/\2/\1' has no escapes to process. Named groups use \k<name>.

Slicing and indexing

Square brackets are the Swiss Army knife for pulling pieces out of a string.

Ruby Slicing with brackets

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Indexing works with a single index, a start and length, a range, a substring or a regex. Assigning to a slice replaces that part. slice! removes and returns a part in place. Positions count characters, not bytes, so "naïve"[2] is "ï".

Padding, alignment and formatting

Ruby Aligning text in columns

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

ljust, rjust and center pad to a width (default pad character is a space, and you may supply one). The % operator on a string is a short form of format, covered in Reading Input and Formatting Output.

Converting and iterating

Ruby Conversions and iteration

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

to_i and to_f never raise: they read as much of the beginning as makes sense and return 0 or 0.0 otherwise. If you want strict conversion that raises on bad input, use Integer("42") and Float("3.5"):

Ruby Strict conversion (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints 42, and the second stops the program with main.rb:2:in 'Kernel#Integer': invalid value for Integer(): "4x2" (ArgumentError).

Encoding basics

Every string knows its encoding. Source code and the default are UTF-8. Use bytes and bytesize to see the raw bytes, valid_encoding? to check for broken data, and encode to convert.

Ruby Encoding queries

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

encode converts the text to another encoding, while force_encoding only relabels the bytes without changing them (use it when you know what the bytes really are). Most programs never leave UTF-8, and the whole standard library assumes it.

Do not use length as the number of letters a user sees. Emoji and accented letters can be several code points: "é" written as e plus a combining accent has length 2. For display width or user-perceived characters, use each_grapheme_cluster.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What does "a,b,,".split(",") return?

    Trailing empty strings are dropped by default. Pass a negative limit such as split(",", -1) to keep them.
  2. 2. What does "hello".sub!("x", "y") return?

    Bang methods return nil when they make no change. That is why chaining a method onto the result of a bang method can raise NoMethodError.
  3. 3. Which call removes only the single trailing newline of a line read with gets?

    chomp removes one trailing line ending. strip also removes whitespace at both ends, and delete would remove every newline in the string.
  4. 4. What is "abc".to_i?

    to_i is forgiving and returns 0 when there is no leading number. Use Integer("abc") when you want an error.
  5. 5. What does "Hello, world"[7..] return?

    Index 7 is the w, and an endless range runs to the end of the string.

Summary

  • ? methods answer yes or no; ! methods change the string in place and return nil when nothing changed.
  • Clean input with strip, chomp, delete_prefix and delete_suffix; break it up with split and rebuild with join.
  • sub replaces the first match, gsub all of them; use a block or a hash for computed replacements and match? for fast tests.
  • Brackets slice by index, range, substring or regex, and assigning to a slice replaces it.
  • ljust, rjust, center and % align and format text.
  • to_i/to_f are forgiving; Integer()/Float() are strict.
  • Strings carry an encoding (UTF-8 by default): length counts characters and bytesize counts bytes.

Next: Symbols