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

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

问题描述

这红宝石code未表现为我所期望的:

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的排序不就地进行排序。 (你有一个Python的背景,也许?)

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

Ruby有排序!就地分拣,但没有就地变种 sort_by 。在实践中,你可以这样做:

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

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

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

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