Home > Software engineering >  How do I split a string with two different delimiters in Ruby and convert it to two arrays?
How do I split a string with two different delimiters in Ruby and convert it to two arrays?

Time:12-29

I have a string

"Param 1: 1, Some text: 2, Example3: 3, Example4: 4"

and I'd like to convert it into an arrays:

["Param 1","Some text","Example3","Example4"]
[1,2,3,4]

How?

CodePudding user response:

There are plenty of ways to do it in Ruby.

You can first split by pairs' delimiter (comma) and then use map to split further by key/pair delimiter (colon):

pairs = s.split(/,\s*/).map { |s| s.split(/:\s*/) }
keys = pairs.map(&:first)
values = pairs.map(&:last)

(here and below s is your original string)

You can use scan to match keys/values in a single call (disclaimer: it does NOT mean this is more efficient - regexps aren't magic)

pairs = s.scan(/(?<key>[^:] ):\s*(?<value>[^,] )[,\s]*/)
keys = pairs.map(&:first)
values = pairs.map(&:last)

(named captures aren't necessary here - with scan they don't give any benefits - but I put them to make regexp arguably a bit more readable)

You can split by all delimiters and then use Enumerable#partition to separate keys from values, smth. like:

keys, values = s.split(/:\s*|,\s*/).partition.with_index { |_, i| i.even? }

etc...

CodePudding user response:

Input

a = "Param 1: 1, Some text: 2, Example3: 3, Example4: 4"

Code

obj= a.split(',').map { |x| x.split(':') }    
p obj.map(&:first).map(&:strip)    
p obj.map(&:last)

Result

["Param 1", "Some text", "Example3", "Example4"]
[" 1", " 2", " 3", " 4"]
  • Related