I want to split a string suppressing all null fields

Command:

",1,2,,3,4,,".split(',')

Result:

["", "1", "2", "", "3", "4", ""]

Expected:

["1", "2", "3", "4"]

How to do this?


Edit

Ok. Just to sum up all that good questions posted.

What I wanted is that split method (or other method) didn't generate empty strings. Looks like it isn't possible.

So, the solution is two step process: split string as usual, and then somehow delete empty strings from resulting array.

The second part is exactly this question (and its duplicate)

So I would use

",1,2,,3,4,,".split(',').delete_if(&:empty?) 

The solution proposed by Nikita Rybak and by user229426 is to use reject method. According to docs reject returns a new array. While delete_if method is more efficient since I don't want a copy. Using select proposed by Mark Byers even more inefficient.

steenslag proposed to replace commas with space and then use split by space:

",1,2,,3,4,,".gsub(',', ' ').split(' ')

Actually, the documentation says that space is actually a white space. But results of "split(/\s/)" and "split(' ')" are not the same. Why's that?

Mark Byers proposed another solution - just using regular expressions. Seems like this is what I need.

Edit
Report