How do I remove non-breaking spaces (\u00A0) from an array in Ruby?

I have an array that contains non-breaking spaces that I want to get rid of. I want to either strip them as it goes into the array or remove them once in. The solution needs to retain regular spaces and nil entries will end up in the array.

Whatever I try the array remains unchanged. I am just learning Ruby and not really a coding superstar to start off with but I’m trying! :slight_smile:

Here is what I have:

myarray = [“foo\u00A0”, “foo bar\u00A0”, “foo foo bar\u00A0”]

I want to end up with:

myarray = [“foo”, “foo bar”, “foo foo bar”]

I have tried:

myarray.map {|word| word.gsub(’\u00A0’,’’) }

and

myarray.map {|word| word.gsub(’/[[:space:]]/’,’’) }

Any help is appreciated.

Edited to correct some of the slashes I had going in the wrong direction

Shouldn’t /u00A0 be \u00A0 instead?

To remove the trailing spaces (\s), carriage returns (\r) and new line characters (\n), you can use the String#strip method. But you have unicode characters in the end, so you can use the String#delete_suffix! method for that:

myarray = ["foo\u00A0", "foo bar\u00A0", "foo foo bar\u00A0"]
myarray.each { |x| x.delete_suffix!("\u00A0".freeze) }
p myarray    # => ["foo", "foo bar", "foo foo bar"]
1 Like

Thanks for your help, that worked perfectly!

Yes, you’re right it was supposed to be \u00A0… LOL. I was, and still am, tired from wrestling with this and a couple of other problems I’m having. Every time I stick a bb in my head, another one falls out the other side!

Now onto the next hurdle!