如何通过散列中的值对散​​列数组进行排序?

Oll*_*ass 113 ruby arrays sorting hash

这个Ruby代码的行为不像我期望的那样:

# create an array of hashes
sort_me = []
sort_me.push({"value"=>1, "name"=>"a"})
sort_me.push({"value"=>3, "name"=>"c"})
sort_me.push({"value"=>2, "name"=>"b"})

# sort
sort_me.sort_by { |k| k["value"]}

# same order as above!
puts sort_me
Run Code Online (Sandbox Code Playgroud)

我正在寻找按键"值"对哈希数组进行排序,但它们是未分类打印的.

Sté*_*hen 205

Ruby sort没有就地排序.(你有Python背景吗?)

Ruby具有sort!就地排序功能,但没有就地变种sort_by.在实践中,您可以:

sorted = sort_me.sort_by { |k| k["value"] }
puts sorted
Run Code Online (Sandbox Code Playgroud)

  • 实际上,`Array#sort_by!`是Ruby 1.9.2中的新功能.今天可以通过要求我的`backports`宝石获得所有Ruby版本:-) (26认同)
  • @tekknolagi:只需追加`.reverse`. (8认同)
  • 你不能用`sort_by`做到这一点,但是使用`sort`或`sort!`并简单地翻转操作数:`a.sort!{| X,Y | y <=> x}`(http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-sort) (2认同)
  • 或者:`puts sorted = sort_me.sort_by{ |k,v| v }` (2认同)

bjg*_*bjg 21

根据@shteef,但sort!根据建议使用变体实现:

sort_me.sort! { |x, y| x["value"] <=> y["value"] }
Run Code Online (Sandbox Code Playgroud)


小智 6

虽然Ruby没有sort_by就地变体,但您可以:

sort_me = sort_me.sort_by { |k| k["value"] }
Run Code Online (Sandbox Code Playgroud)

Array.sort_by! 在1.9.2中添加