Nodir Nasirov Nodir Nasirov - 3 months ago 15
Ruby Question

Replacing non standard characters in ruby

I have an array of strings:

strings = ["\u2014 some text", "\u00A0 Foo", "Bar"]


What statement should I write in order to get an array that looks like this:

strings = [" some text", " Foo", "Bar"]


I tried following, but no luck:

strings.map!{|string| string.gsub!(/(Wu2014|Wu00A0)/, '')}

Answer

If you want to remove non-ASCII chars, then

strings.map{| s | s.encode('ASCII', 'binary', invalid: :replace, undef: :replace, replace: '')}