How to Extract a Substring from a String in Ruby

Contents
In this article, you will learn how to extract a substring from a string in Ruby.
Extracting a substring from a string
In Ruby, you can extract a substring from a string using the slice or [] method. Here’s an example:
string = "Hello, world!"
substring = string.slice(0, 5) # "Hello"
In the above example, slice takes two arguments: the starting index and the length of the substring. Alternatively, you can use [] method like below:
string = "Hello, world!"
substring = string[0, 5] # "Hello"
Here, [] also takes two arguments: the starting index and the length of the substring. You can also use a range of indices to extract a substring:
string = "Hello, world!"
substring = string[0..4] # "Hello"
Here, the .. operator creates a range from the starting index to the ending index, inclusive.
You can also use regular expressions to extract substrings that match a specific pattern:
string = "Hello, world!"
substring = string[/\w+/] # "Hello"
In this example, the regular expression \w+ matches one or more word characters (letters, digits, and underscores). The [] method returns the first match it finds.
Here are a few more details on extracting substrings in Ruby:
-
You can use negative indices to start from the end of the string. For example:
string = "Hello, world!" substring = string[-6..-2] # "world"
-
If you only need to extract a single character, you can use the [] method with a single index:
string = "Hello, world!" char = string[1] # "e"
-
If you want to extract a substring starting from a specific index to the end of the string, you can omit the length argument:
string = "Hello, world!" substring = string[7..] # "world!"
- The slice and [] methods are equivalent and can be used interchangeably. You can choose the one that you find more readable.
-
If you need to extract multiple substrings that match a pattern, you can use the scan method with a regular expression:
string = "Hello, world!" matches = string.scan(/\w+/) # ["Hello", "world"]
In this example, the scan method returns an array of all matches of the regular expression \w+.