Ruby Q & A

 

How to split a string into an array in Ruby?

In Ruby, you can split a string into an array using the `.split` method. This method allows you to divide a string into substrings based on a specified delimiter or pattern and store those substrings as elements in an array. Here’s how you can use it:

  1. Splitting by a Delimiter:

To split a string into an array of substrings based on a specific delimiter (such as a space, comma, or any other character), you can simply call `.split` on the string and pass the delimiter as an argument.

 ```ruby

   text = "apple,banana,kiwi"

   fruits = text.split(",")

   ```

In this example, the string `text` is split into an array of fruits using the comma `,` as the delimiter. The resulting `fruits` array will contain `[“apple”, “banana”, “kiwi”]`.

 

  1. Splitting by Whitespace (Default):

If you don’t specify a delimiter, `.split` by default splits the string by whitespace characters (spaces, tabs, and line breaks).

 ```ruby

   sentence = "This is a sample sentence."

   words = sentence.split

   ```

Here, `words` will be an array containing `[“This”, “is”, “a”, “sample”, “sentence.”]`.

 

  1. Splitting by Regular Expression:

You can also split a string using a regular expression pattern to match specific substrings.

 ```ruby

   text = "apple123banana456kiwi"

   substrings = text.split(/\d+/)

   ```

In this case, the regular expression `/\\d+/` matches one or more digits, effectively splitting the string into substrings separated by numbers. The `substrings` array will contain `[“apple”, “banana”, “kiwi”]`.

The `.split` method is versatile and allows you to manipulate strings by dividing them into manageable parts. Whether you need to process CSV data, split sentences into words, or extract content based on a pattern, `.split` is a valuable tool for working with strings in Ruby.

Previously at
Flag Argentina
Chile
time icon
GMT-3
Experienced software professional with a strong focus on Ruby. Over 10 years in software development, including B2B SaaS platforms and geolocation-based apps.