Ruby claims " " isn't actually a space?

Viewed 55

I'm trying to troubleshoot why Ruby isn't splitting my string by empty spaces. For example:

[1] pry(#<irb>)> msg
=> "!iex <http://test-domain.com.au|test-domain.com.au> <mailto:first.last@test-domain.com.au|first.last@test-domain.com.au> FirstName"
[2] pry(#<irb>)> msg.split(" ")
=> ["!iex <http://test-domain.com.au|test-domain.com.au> <mailto:first.last@test-domain.com.au|first.last@test-domain.com.au> FirstName"]
[3] pry(#<irb>)> msg.include? " "
=> false
[8] pry(#<irb>)> msg.inspect
=> "\"!iex <http://test-domain.com.au|test-domain.com.au> <mailto:first.last@test-domain.com.au|first.last@test-domain.com.au> FirstName\""
[9] pry(#<irb>)> 

As you can see above, my string appears to contain spaces, but the split method isn't working on it. I tried to run inspect on the string just to see if something else was being displayed, but it doesn't really make a lot of sense to me.

1 Answers

Either the string contains some other kind of whitespace or you're splitting on some other kind of whitespace. For example "foo\u2002bar" will look like foo bar but contains a special space.

Try msg.dump to see the special characters.

2.6.5 :008 > msg = "foo\u2002bar"
 => "foo bar" 
2.6.5 :009 > msg.dump
 => "\"foo\\u2002bar\"" 

To split on any space or tab, split on the [[:blank:]] character class.

2.6.5 :006 > msg.split(/[[:blank:]]/)
 => ["foo", "bar"] 
Related