Last Updated: February 25, 2016
·
6.074K
· muszynskis

Rails: Upcase/downcase for Non-ASCII Strings

Introduction

Upcase/downcase method for ASCII strings works pretty good.

"turtle".upcase      
=> "TURTLE"

"TURTLE".downcase     
=> "turtle"

Problem

=
Polish translation of "turtle" is "żółw". Let's try to upcase it:

"żółw".upcase       
=> "żółW"

What about downcase?

"ŻÓŁW".downcase
=> "ŻÓŁw"

As we can see, upcase/downcase method doesn't work properly for string containing non-ASCII characters.

Solution

Rails give us helpful method - mb_chars.

"żółw".mb_chars.upcase
=> "ŻÓŁW"
"ŻÓŁW".mb_chars.downcase
=> "żółw"

Now, it works!

Click here to read more about mb_chars.