如何在 ruby 中对哈希数组进行排序 [英] How to sort an array of hashes in ruby
本文介绍了如何在 ruby 中对哈希数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,它的每个元素都是一个包含三个键/值对的散列:
I have an array, each of whose elements is a hash with three key/value pairs:
:phone => "2130001111", :zip => "12345", :city => "sometown"
我想按 zip
对数据进行排序,以便同一区域中的所有 phone
都在一起.Ruby 有没有一种简单的方法来做到这一点?will_paginate
可以对数组中的数据进行分页吗?
I'd like to sort the data by zip
so all the phone
s in the same area are together. Does Ruby have an easy way to do that? Can will_paginate
paginate data in an array?
推荐答案
简单:
array_of_hashes.sort_by { |hsh| hsh[:zip] }
注意:
当使用 sort_by
时,您需要将结果分配给一个新变量:array_of_hashes = array_of_hashes.sort_by{}
否则您可以使用bang"方法进行修改地点:array_of_hashes.sort_by!{}
When using sort_by
you need to assign the result to a new variable: array_of_hashes = array_of_hashes.sort_by{}
otherwise you can use the "bang" method to modify in place: array_of_hashes.sort_by!{}
这篇关于如何在 ruby 中对哈希数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文