Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby split by comma absorbing trailing space

Tags:

regex

split

ruby

I need to split a string into two variables. For example, the following would work fine:

first,second = "red,blue".split(',')

I would like to split user input, which might have an optional space after the comma. How do I write it so a space after the comma is absorbed? I need to correctly handle all these possibilities:

"red,blue"        # first="red" second="blue"
"red, blue"       # first="red" second="blue"
"red,dark blue"   # first="red" second="dark blue"
"red, light blue" # first="red" second="light blue"
like image 472
Andrew Avatar asked Mar 06 '12 00:03

Andrew


People also ask

How do you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

How do you split a character in a string in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

What is a delimiter Ruby?

Delimiters: one or more characters that separate text strings (from Computer Hope). Ruby Regular Expressions (regex): helps us to find particular patterns inside a string; they are declared between two forward slashes “/ /” and its equivalent regex literal is %r{…} (from GeeksforGeeks)


1 Answers

Just trim the resulting entries. The way you do this depends on whether you want to support exactly one space after the comma, or whether you want to remove all leading whitespace (and maybe trailing whitespace too). If your goal is to get words, like it looks like in your sample, you should just remove all surrounding whitespace.

first,second = "red, blue".split(',').map(&:strip)
like image 172
Lily Ballard Avatar answered Nov 03 '22 06:11

Lily Ballard