Ruby split by comma absorbing trailing space Ruby split by comma absorbing trailing space ruby ruby

Ruby split by comma absorbing trailing space


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)


There is no regexp in your code - you split using a string, which makes a difference."red,blue".split(/\s*,\s*/) should work as you expect.


list.split(/, */) 

This is a regular expression that works with or without a space after the comma.