Real upcase and downcase methods in Ruby

Changing the case of unicode strings makes a mistake. Let's fix it!

Mar 27

If you need to store non-english text in String variables, you will notice that it is difficult to change the case of unicode strings.

Let's see in irb:

irb(main):001:0> a="árvíztűrő tükörfúrógép"
=> "árvíztűrő tükörfúrógép"
irb(main):002:0> a.upcase
=> "áRVíZTűRő TüKöRFúRóGéP"
irb(main):003:0> require 'active_support/core_ext/string'
=> true
irb(main):004:0> a.mb_chars.upcase.to_s
=> "ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP"

We can overwrite the methods in String class for comfortable use:

require 'active_support/core_ext/string'

class Srting
  def upcase
    self.mb_chars.upcase.to_s
  end
  def capitalize
    self.mb_chars.capitalize.to_s
  end
end

Next Post Previous Post