Sorting UTF-8 strings in RoR

前端 未结 7 891
暗喜
暗喜 2020-12-09 18:12

I am trying to figure out a \'proper\' way of sorting UTF-8 strings in Ruby on Rails.

In my application, I have a select box that is populated with countries. As my

7条回答
  •  北海茫月
    2020-12-09 18:41

    There are a couple of ways to go. You may want to convert the UTF strings to hex strings and then sort them:

    s.split(//).collect { |x| x.unpack('U').to_s }.join
    

    or you may use the library iconv. Read up on it and use it as appropriate (from dzone):

    #add this to environment.rb
    #call to_iso on any UTF8 string to get a ISO string back
    #example : "Cédez le passage aux français".to_iso
    
    class String
      require 'iconv' #this line is not needed in rails !
      def to_iso
        Iconv.conv('ISO-8859-1', 'utf-8', self)
      end
    end
    

提交回复
热议问题