如何按散列中的值对散​​列数组进行排序? [英] How do I sort an array of hashes by a value in the hash?

查看:43
本文介绍了如何按散列中的值对散​​列数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段 Ruby 代码的行为不像我预期的那样:

This Ruby code is not behaving as I would expect:

# 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

我希望通过键值"对散列数组进行排序,但它们打印时未排序.

I'm looking to sort the array of hashes by the key "value", but they are printed unsorted.

推荐答案

Ruby 的 sort 不能就地排序.(也许你有 Python 背景?)

Ruby's sort doesn't sort in-place. (Do you have a Python background, perhaps?)

Ruby 有 sort! 用于就地排序,但在 Ruby 1.8 中没有 sort_by 的就地变体.在实践中,你可以这样做:

Ruby has sort! for in-place sorting, but there's no in-place variant for sort_by in Ruby 1.8. In practice, you can do:

sorted = sort_me.sort_by { |k| k["value"] }
puts sorted

从 Ruby 1.9+ 开始,.sort_by! 可用于就地排序:

As of Ruby 1.9+, .sort_by! is available for in-place sorting:

sort_me.sort_by! { |k| k["value"]}

这篇关于如何按散列中的值对散​​列数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆