Mike Mike - 1 year ago 76
Ruby Question

Foolproof way to strip whitespace from a Ruby variable?

I'm using Ruby on Rails 4.2.7. I'm having trouble stripping off white space from a variable. I can't tell what kind of white space it is. Is there a foolproof strip method? When I cut and paste from a certain variable I’m unable to strip the white space but, when I type the space, then everything is okay. See my console below:

2.3.0 :004 > test = " 21"
=> " 21"
2.3.0 :005 > test.strip
=> " 21"

I have cut and paste from another source and the white space isn’t being stripped off. Is there a way I can have some kind of foolproof strip method for my variables?

Answer Source

You probably have a non-ASCII Unicode whitespace character, most likely 0x00A0:

> test = "\u00A021"
 => " 21" 
> test.strip
 => " 21" 

and String#strip only (currently) knows about ASCII whitespace:

strip → new_str

Whitespace is defined as any of the following characters: null, horizontal tab, line feed, vertical tab, form feed, carriage return, space.

You can do it by hand with String#gsub and the Space character property:

> test = "\u00A0 21 \t\u00a0"
 => "  21 \t " 
> test.gsub(/\A\p{Space}+|\p{Space}+\z/, '')
 => "21" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download