Ruby String accent error: More than meet the eyes

Posted by Fabiano PS on Stack Overflow See other posts from Stack Overflow or by Fabiano PS
Published on 2010-03-04T13:58:29Z Indexed on 2010/04/08 12:43 UTC
Read the original article Hit count: 670

I'm having a real trouble to get accents right, and I believe this may happen to most Latin languages, in my case, portuguese

I have a string that come as parameter and I must get the first letter and upcase it! That should be trivial in ruby, but here is the catch:

s1 = 'alow'; s1.size #=> 4
s2 = 'álow'; s2.size #=> 5

s1[0,1] #=> "a"
s2[0,1] #=> "\303"

s1[0,1].upcase #=> 'A'
s2[0,1].upcase #=> '\303' !!!

s1[0,1].upcase + s1[1,100] #=> "Alow" OK
s2[0,1].upcase + s2[1,100] #=> "álow" NOT OK

I'd like to make it generic, Any help?

[EDIT]
I found that Rails Strings can be cast to Multibytes as seen in class ../active_support/core_ext/string/multibyte.rb, just using:

s2.mb_chars[0,1].upcase.to_s #=> "Á"

Still, @nsdk approach is easier to use =)

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails