Rails的Hash数组怎么根据某一值来排序

udasker_pictureudasker 213天前更新 0 浏览 1 关注

如题: Rails的Hash数组怎么根据某一值来排序,示例:

a = [
   {:a=>1, :b=>4, :c=>6},
   {:a=>4, :b=>5, :c=>3}, 
   {:a=>3, :b=>6, :c=>5}, 
   {:a=>2, :b=>3, :c=>4}
 ]

怎么分别根据 a,b,c的大小来排序呢?

udasker_picture
做有意义的事
213天前更新

#升序排列

a.sort_ by {|k| k[:c]}

#结果

 [{:a=>4, :b=>5, :c=>3}, {:a=>2, :b=>3, :c=>4}, {:a=>3, :b=>6, :c=>5}, {:a=>1, :b=>4, :c=>6}] 

#降序排序

a.sort_ by {|k| k[:c]}.reverse

#结果
Rbuy [{:a=>1, :b=>4, :c=>6}, {:a=>3, :b=>6, :c=>5}, {:a=>2, :b=>3, :c=>4}, {:a=>4, :b=>5, :c=>3}]