How to Use the split Method in Ruby

09/21/2021

Contents

In this article, you will learn how to use the split method in Ruby.

The split Method

In Ruby, the split method is used to split a string into an array of substrings based on a specified delimiter. Here’s how you can use the split method in Ruby:

# Syntax
string.split(delimiter, limit)

# Example
string = "Hello, world!"
array = string.split(", ") # splits the string at the comma followed by a space
puts array.inspect # output: ["Hello", "world!"]

In the example above, we’re splitting the string “Hello, world!” at the comma followed by a space. The resulting array contains two elements: “Hello” and “world!”.

The split method can take two optional arguments:

  • delimiter: This is the character or string that is used to split the string. If you don’t specify a delimiter, the string will be split at each whitespace character (i.e., spaces, tabs, and newlines).
  • limit: This specifies the maximum number of substrings to return. If you specify a limit, the resulting array will contain no more than limit elements.

Here are a few more examples of how you can use the split method:

string = "one,two,three,four,five"
array = string.split(",") # splits the string at commas
puts array.inspect # output: ["one", "two", "three", "four", "five"]

string = "Hello\nworld\n!"
array = string.split("\n") # splits the string at newlines
puts array.inspect # output: ["Hello", "world", "!"]

string = "one,two,three,four,five"
array = string.split(",", 3) # splits the string at commas, returning no more than 3 elements
puts array.inspect # output: ["one", "two", "three,four,five"]