ruby中的Hash排序

参考:
https://blog.csdn.net/xing102172/article/details/9163607

For example:

h={'a'=>2, 'c'=>1, 'b'=>3}

sort 方法:

key升序:

h.sort { |a, b|  a[0]<=>b[0] }
[["a", 2], ["b", 3], ["c", 1]]

key降序:

h.sort { |a, b|  b[0]<=>a[0] }
[["c", 1], ["b", 3], ["a", 2]]

value升序:

h.sort { |a, b|  a[1]<=>b[1] }
[["c", 1], ["a", 2], ["b", 3]]

value降序:

h.sort { |a, b|  b[1]<=>a[1] 
[["b", 3], ["a", 2], ["c", 1]]

sort_by方法:

value升序:

h.sort_by {|key,value| value}
[["c", 1], ["a", 2], ["b", 3]]

value降序:

h.sort_by {|key,value| -value}
[["b", 3], ["a", 2], ["c", 1]]

key升序:

h.sort_by {|key,value| key}
[["a", 2], ["b", 3], ["c", 1]]

更多参考下面
https://blog.csdn.net/kavin_luo/article/details/72677726

Array 数组的排序

ruby 中数组的用处很多,数组中的元素可以是数字、字符、哈希、数组等
1、单属性排序

a = [1,4,5,7,3,2,8]

a.sort_by do |p|
p
end

输出结果:[1, 2, 3, 4, 5, 7, 8]

a = [{:x=>3,:y=>2,:z=>1},{:x=>3,:y=>1,:z=>3},{:x=>1,:y=>3,:z=>2}]

a.sort_by do |p|
p[:x]
end

输出结果:[{:x=>1, :y=>3, :z=>2}, {:x=>3, :y=>1, :z=>3}, {:x=>3, :y=>2, :z=>1}]
2、多层次排序

a = [{:x=>3,:y=>2,:z=>1},{:x=>3,:y=>1,:z=>3},{:x=>1,:y=>3,:z=>2}]

a.sort_by do |p|
[p[:x],p[😒]]
end

输出结果:[ {:x => 1, :y =>3, 😒 => 2}, {:x => 3, :y =>2, 😒 => 1}, {:x => 3, :y => 1, 😒 => 3} ]

在Rails里,我们可以用sort_by方法对一个Ruby对象数组按照某个属性 进行排序

User.all.sort_by{|u| u.created_at}

上面的写法等效于

User.all.sort{|a,b| a.created_at <=> b.created_at}

https://blog.csdn.net/a675697174/article/details/51984638

[Haima的博客] http://www.cnblogs.com/haima/
posted @ 2021-08-28 01:37  HaimaBlog  阅读(13)  评论(0编辑  收藏  举报