ruby的sort方法的重新认识

ruby中的sort方法,这个方法可以加一个两个参数的block,这个block可以返回1 0 -1来表示这两个参数大于 等于 小于
示例:

str = ["192.160.175","192.160.90","192.168.2.175","192.168.2.90","192.168.1.180","192.160.90.1"]

arr = str.sort do |a, b|
    ip1 = a.split('.').map &:to_i
    ip2 = b.split('.').map &:to_i
    ret = 0
    ip1.each_with_index do |ip, i|
      if ip2[i].nil?
        ret = 1
        break
      end
      if ip != ip2[i]
        ret = ip <=> ip2[i]
        break
      end
    end
    ret = ret == 0 && ip1.size > ip2.size ? 1 : ret
end
p arr

输出:

["192.160.90","192.160.175","192.160.90.1","192.168.1.180","192.168.2.90","192.168.2.175"]

 

posted on 2013-09-13 11:09  张飞_  阅读(2544)  评论(0编辑  收藏  举报

导航