4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【ruby】汉字数字排序

Last updated at Posted at 2016-01-20

在制作地址系统时,遇到需要将地址的丁目大小从小到大排序显示的问题。由于数据库地址中的丁目信息是按照汉字数字的形式进行储存,而系统并非根据汉字数字所代表的数字大小来进行排序,因此只能通过简单的手动排序来进行处理。

  def sort_by_number(array)
    number_char = {
      "零" => 0, "一" => 1, "二" => 2,
      "三" => 3, "四" => 4, "五" => 5,
      "六" => 6, "七" => 7, "八" => 8,
      "九" => 9, "十" => 10
    }
    
    array.sort do |a, b|
      number_char[a[0]] <=> number_char[b[0]]
    end
  end
  
  array = %w(一丁目 四丁目 三丁目 二丁目)
  # => ["一丁目", "四丁目", "三丁目", "二丁目"]
  
  array.sort{ |a, b| a[0] <=> b[0] }
  # => ["一丁目", "三丁目", "二丁目", "四丁目"]
  
  sort_by_number array
  # => ["一丁目", "二丁目", "三丁目", "四丁目"]
  • TODO: 该算法不支持大小为十以上的汉字数字的排序,等有时间再进行改进。

UPDATE: 使用Gem ZenTol将汉字转化为数字后进行排序

gem 'zen_to_i'

对上述代码进行简化

require 'zen_to_i'

def sort_by_number(array)
  array.sort_by do |str|
    str.zen_to_i.to_i
  end
end

array = %w(一丁目 四丁目 十丁目 十三丁目 二丁目)
#=> ["一丁目", "四丁目", "十丁目", "十三丁目", "二丁目"]
sort_by_number array
#=> ["一丁目", "二丁目", "四丁目", "十丁目", "十三丁目"]
4
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?