ruby-on-rails - 根据项目数组对 Rails 哈希进行排序

标签 ruby-on-rails arrays hash

我有一个像这样的数组:

['one','three','two','four']

我有一个像这样的哈希数组:

[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc...

我想按第一个数组对哈希数组进行排序。我知道我能做到:

array_of_hashes.sort_by{|k,v| k.to_s} to sort them and it will sort by the key 

(以及将 :total 转换为字符串的 .to_s )

我怎样才能做到这一点?

编辑:

我对它的设置方式有误,实际上是这样的:

{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} }

如果我需要将其放入新问题中,请告诉我,我会这样做。

谢谢

最佳答案

与 ctcherry 答案类似,但使用 sort_by。

sort_arr = ['one','three','two','four']
hash_arr = [{'three' => {..some data here..} }, {'two' => {..some data here..} }]

hash_arr.sort_by { |h| sort_arr.index(h.keys.first) }

关于ruby-on-rails - 根据项目数组对 Rails 哈希进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5490892/

相关文章:

php - 使用另一个数组作为输入对数组进行排序

ruby - 我需要做什么才能让 Hash.from_xml() 工作?

ruby-on-rails - 如何更正语法突出显示以在 Sublime/Textmate 2 中设置 Rails 链接或表单字段 "class"

ruby-on-rails - PHP 开发人员学习 Ruby 和 Ruby on Rails

c# - 在 .NET 的 HTTP 请求中传递数组值

python - 用负数对 numpy 字符串数组进行排序?

ruby-on-rails - 使用特定日期格式的键检索哈希值

ruby-on-rails - 给观察者动态添加回调方法

ruby-on-rails - 如何在哈希栏中搜索单词

algorithm - 生产中md5碰撞的几个问题