Tespy
Tespy

Reputation: 1005

Ruby string split with space as input removes more than just spaces

I have some text that has this particular character: When I call the string split() method (with just ' ' as the input) , the gets removed. What should I do to keep the ?

Upvotes: 0

Views: 109

Answers (1)

Stefan
Stefan

Reputation: 114158

That's the expected behavior when passing ' '. According to the docs:

If pattern is a single space, str is split on whitespace, with leading and trailing whitespace and runs of contiguous whitespace characters ignored.

With "whitespace" being space (" ") and \t, \n, \v, \f, \r.

"foo bar\nbaz \f qux".split(' ')
#=> ["foo", "bar", "baz", "qux"]

To split on space (U+0020) only, you have to use a regexp:

"foo bar\nbaz \f qux".split(/ /)
#=> ["foo", "bar\nbaz", "\f", "qux"]

Upvotes: 2

Related Questions