Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's String#gsub, unicode, and non-word characters

As part of a larger series of operations, I'm trying to take tokenized chunks of a larger string and get rid of punctuation, non-word gobbledygook, etc. My initial attempt used String#gsub and the \W regexp character class, like so:

my_str = "Hello,"
processed = my_str.gsub(/\W/,'')
puts processed # => Hello

Super, super, super simple. Of course, now I'm extending my program to deal with non-Latin characters, and all heck's broken loose. Ruby's \W seems to be something like [^A-Za-z0-9_], which, of course, excludes stuff with diacritics (ü, í, etc.). So, now my formerly-simple code crashes and burns in unpleasent ways:

my_str = "Quística."
processed = my_str.gsub(/\W/,'')
puts processed # => Qustica

Notice that gsub() obligingly removed the accented "í" character. One way I've thought of to fix this would be to extend Ruby's \W whitelist to include higher Unicode code points, but there are an awful lot of them, and I know I'd miss some and cause problems down the line (and let's not even start thinking about non-Latin languages...). Another solution would be to blacklist all the stuff I want to get rid of (punctuation, $/%/&/™, etc.), but, again, there's an awful lot of that and I really don't want to start playing blacklist-whack-a-mole.

Has anybody out there found a principled solution to this problem? Is there some hidden, Unicode-friendly version of \W that I haven't discovered yet? Thanks!

like image 815
Steven Bedrick Avatar asked Oct 26 '09 22:10

Steven Bedrick


People also ask

What is Ruby string?

In Ruby, string is a sequence of one or more characters. It may consist of numbers, letters, or symbols. Here strings are the objects, and apart from other languages, strings are mutable, i.e. strings can be changed in place instead of creating new strings.

How do you get a string in Ruby?

Strings exist within either single quotes ' or double quotes " in Ruby, so to create a string, enclose a sequence of characters in one or the other: 'This is a string in single quotes. ' "This is a string in double quotes." You can choose to use either single quotes or double quotes.

How do you assign a string in Ruby?

Changing a Section of a String Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.


1 Answers

You need to run ruby with the "-Ku" option to make it use UTF-8. See the documentation for command-line options. This is what happens when I do this with irb:

% irb -Ku
irb(main):001:0> my_str = "Quística."
=> "Quística."
irb(main):002:0> processed = my_str.gsub(/\W/,'')
=> "Quística"
irb(main):003:0> 

You can also put it on the #! line in your ruby script:

#!/usr/bin/ruby -Ku
like image 100
wdebeaum Avatar answered Sep 19 '22 07:09

wdebeaum