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"
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.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With