Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. String.slice / []

String.slice / []

A method that extracts a portion of a string. slice and [] (bracket notation) both perform the same operation.

Syntax

# Extract by specifying a start index and length.
string.slice(start_index, length)
string[start_index, length]

# Extract using a range object.
string[start..end]
string[start...end]  # Excludes the end index

# Extract by specifying a substring.
string[search_string]

Method List

NotationDescription
str[n]Returns the character at index n. A negative value counts from the end of the string.
str[n, len]Extracts len characters starting from index n and returns them.
str[n..m]Extracts the range from index n to m, inclusive.
str[n...m]Extracts from index n up to, but not including, index m.
str[substr]Returns the portion of the string that matches the substring. Returns nil if not found.

Sample Code

text = "Hello, Ruby!"

# Extract by index and length.
puts text[0, 5]    # Hello
puts text[7, 4]    # Ruby

# Extract by range.
puts text[0..4]    # Hello
puts text[0...5]   # Hello (excludes the end index)

# Use a negative index to count from the end.
puts text[-5, 4]   # Ruby
puts text[-1]      # ! (the last character)

# Works the same way with Unicode text.
greeting = "Good morning"
puts greeting[0, 4]   # Good
puts greeting[5..]    # morning (endless range, Ruby 2.6+)

# Specify a substring.
puts text["Ruby"]          # Ruby
puts text["Java"].inspect  # nil

# Extract year, month, and day from a date string.
date = "2024-03-15"
puts date[0, 4]   # 2024 (year)
puts date[5, 2]   # 03 (month)
puts date[8, 2]   # 15 (day)

Notes

In Ruby, the [] notation is the most commonly used way to extract substrings. slice provides the same functionality in method form. If you specify an out-of-bounds index, nil may be returned, so always check the return value when using dynamic indexes.

Ruby 2.6 and later support endless ranges such as str[n..], which retrieves all characters from index n onward. You can also pass a regular expression as the argument (e.g., str[/\d+/]).

To split a string into an array, use split. To get the length of a string, use length / size.

If you find any errors or copyright issues, please .