Latest Tweets:

Ruby - Splitting a string on multiple delimiters

Sometimes you have a string you want to split but the delimiters could be multiple, e.g. a newline, a comma, a semicolon. Using a regex in Ruby’s String#split function, we can split on multiple delimiters. 

In the example below, we would like to split our test_string on a period, comma and semicolon. 

» test_string = “xyz.123,457;abc”

» test_string.split(/,|\.|;/)

» [“xyz”, “123”, “457”, “abc”]

Gotta love regexes.