Pranav Reddy Pranav Reddy - 6 months ago 12
Ruby Question

Ruby Split on Two String Delimters

How would I split a string based on two string delimiters like " of " and " in ".

For example, the string:

"dogs in Toronto of Canada"


would transform into array:

["dogs", "Toronto", "Canada"]

Answer

You can use String#split with regex:

"dogs in Toronto of Canada".split(/\sof\s|\sin\s/)
=> ["dogs", "Toronto", "Canada"]