• ruby中Hash排序


    当values都是整形时,按照Hash的Values排序:

    h = {'a'=>1,'b'=>2,'c'=>5,'d'=>4}

    h.sort {|a,b| a[1]<=>b[1]}

    输出:[["a", 1], ["b", 2], ["d", 4], ["c", 5]]

     

    当我们需要对Hash进行排序时,不能像数组那样简单的使用sort方法,因为数组中的数据类型都是一样的(整型),Hash中的数据类型可能并不完全一样,如整数类型和字符串类型就没法一起排序,此时就需要我们进行处理,如下(如果Hash中的数据类型全部相同可以不进行如下处理):

           def sorted_hash(aHash)

                  return aHash.sort{

                         |a,b|  a.to_s <=> b.to_s                     

                  }

           End

    h1 = {1=>'one', 2=>'two', 3=> 'three'}

    h2 = {6=>'six', 5=>'five', 4=> 'four'}

    h3 = {'one'=>'A', 'two'=>'B','three'=>'C'}

    h4 = h1.merge(h2)                      #合并hash

    h5 = h1.merge(h3)

    def sorted_hash(aHash)

       return aHash.sort{|a,b| a.to_s <=> b.to_s  }

    end

    p(h4)                   

    p(h4.sort)

    p(h5)

    p(sorted_hash(h5))

    ----------------Result---------------

    {5=>"five", 6=>"six", 1=>"one", 2=>"two", 3=>"three", 4=>"four"}

    [[1, "one"], [2, "two"], [3, "three"], [4, "four"], [5, "five"], [6, "six"]]

    {"two"=>"B", "three"=>"C", 1=>"one", 2=>"two", "one"=>"A", 3=>"three"}

    [[1, "one"], [2, "two"], [3, "three"], ["one", "A"], ["three", "C"], ["two", "B"]]

    事实上Hash的sort方法是把一个Hash对象转换成以[key,value]为单个元素的一个数组,然后再用数组的sort方法进行排序。

  • 相关阅读:
    (转)-为什么分布式一定要有Redis?
    (九)redis使用lua脚本
    (八)redis实现分布式锁
    (七)面试题-Redis比较常见的面试题-转载
    (六)redis缓存穿透,击穿,雪崩以及解决方案
    (五)redis的主从复制
    (四)redis的数据持久化-RDB,AOF
    (三)redis的其他功能-Bitmap,HyperLogLog,GEO
    JsTracker
    Web开发者助手 FeHelper
  • 原文地址:https://www.cnblogs.com/wangyuyu/p/4128886.html
Copyright © 2020-2023  润新知