为什么 ruby 使用 space 分隔符拆分语句 return 不同的值?

Why do ruby split statements with space separators return different values?

例如这两行除了分隔符 return 不同的数组外完全相同。

"1,2,,3,4,,".split(',')
=> ["1", "2", "", "3", "4"] 
"1 2  3 4  ".split(' ')
=> ["1", "2", "3", "4"] 

因为传递给方法 String#split 的单个空格具有特殊含义。

来自the docs

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

根据您要查找的内容,您可以传入一个空字符串:

 '1 2  3 4  '.split( '' )
 # => ["1", " ", "2", " ", " ", "3", " ", "4", " ", " "] 

或使用正则表达式:

 '1 2  3 4  '.split( /\s/ )
 # => ["1", "2", "", "3", "4"]