Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

Ruby claims " " isn't actually a space?

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:[email protected]|[email protected]> FirstName"
[2] pry(#<irb>)> msg.split(" ")
=> ["!iex <http://test-domain.com.au|test-domain.com.au> <mailto:[email protected]|[email protected]> FirstName"]
[3] pry(#<irb>)> msg.include? " "
=> false
[8] pry(#<irb>)> msg.inspect
=> ""!iex <http://test-domain.com.au|test-domain.com.au> <mailto:[email protected]|[email protected]> 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.

Any help would be greatly appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Try msg.dump to see the special characters.

2.6.5 :008 > msg = "foou2002bar"
 => "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"] 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...