user 32394023 user 32394023 - 2 years ago 156
Ruby Question

Ruby - split by multiple delimiters

I'm receiving a string that contains two numbers and it can be received in a handful of different formats.

"344, 345"
, "
"432 345"

I need to split these into two separate numbers inside an array using
, and then converting using

What I've tried so far:

nums.split(/[\s+,x]/) # split on one or more spaces, a comma or x

However, it doesn't seem to match multiple spaces when testing - also, it doesn't allow for the space in the comma version shown above (
"344, 345"

How can I match multiple delimiters in Ruby? Thank you

Answer Source

You are using a character class in your pattern, and it matches only one character. [\s+,x] matches 1 whitespace, or a +, , or x. You meant to use (?:\s+|x).

However, perhaps, a mere \D+ (1 or more non-digit characters) should suffice:

"345, 456".split(/\D+/).map(&:to_i)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download