haima

参考:
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[

分类:

技术点:

相关文章: