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"]
点亮测试人生!QQ:408129370
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号:
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号: