打印按哈希键排序的哈希数组 [英] Print an array of hashes ordered by a hash key

查看:100
本文介绍了打印按哈希键排序的哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这样的哈希值

{'id' => 'ID001', 'count' => 1}
{'id' => 'ID003', 'count' => 2}
{'id' => 'ID002', 'count' => 1}

我这样做是为了打印列表

I do this to print the list

myarray.each_with_index do |i, p|
    puts "\n #{p+1}) #{i['id']} n. #{i['count'].to_s}"
end

它运行完美,实际上,我得到了:

It works perfectly, in fact, I obtain this:

1) 'ID001' n. 1
2) 'ID003' n. 2
3) 'ID002' n. 1

是否可以通过"ID"键对散列进行排序?

Is it possible to order the hashes by "ID" key?

推荐答案

myarray.
  sort_by { |h| h['id'][/\d+/].to_i }.
  each.
  with_index(1) do |h, idx|
    puts ["\n", "#{idx})", h['id'], "n.", h['count']].join(' ')
  end

这篇关于打印按哈希键排序的哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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