如何按数字值排序Ruby哈希? [英] How to sort a Ruby Hash by number value?

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

问题描述

我有一个计数器散列,我试图按数字排序。我遇到的问题是默认的Hash.sort函数将数字排序为字符串而不是数字大小。



即,给定散列:

  metrics = {sitea.com=> 745,siteb.com=> 9,sitec.com=> 10} 

运行以下代码:

  metrics.sort {| a1,a2 | a2 [1]< => a1 [1]} 

将返回一个排序数组:

  ['siteb.com',9,'sitea.com',745,'sitec.com',10] 

尽管745是一个比9更大的数字,但9将首先出现在列表中。当试图显示谁是最高的人数时,这会让我的生活变得困难。 :)

关于如何通过数值大小排序哈希(或数组)的任何想法?



感谢任何帮助。

解决方案

不知道如何得到结果,因为它不会按字符串值排序...您应该在您的示例中反转 a1 a2

在任何情况下(根据Mladen),最佳方式是:

  metrics = {sitea.com=> 745,siteb.com=> 9,sitec.com=> 10} 
metrics.sort_by {| _key,value |值}
#==> [[siteb.com,9],[sitec.com,10],[sitea.com,745]]

如果您需要散列作为结果,您可以使用 to_h (在Ruby 2.0 +中)

  metrics.sort_by {| _key,value |值} .to_h 
#==> {siteb.com=> 9,sitec.com=> 10,sitea.com,745}


I have a counter hash that I am trying to sort by count. The problem I am running into is that the default Hash.sort function sorts numbers like strings rather than by number size.

i.e. Given Hash:

metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }

Running this code:

metrics.sort {|a1,a2| a2[1]<=>a1[1]}

will return a sorted array:

[ 'siteb.com', 9, 'sitea.com', 745, 'sitec.com', 10]

Even though 745 is a larger number than 9, 9 will appear first in the list. When trying to show who has the top count, this is making my life difficult. :)

Any ideas on how to sort a hash (or an array even) by number value size?

I appreciate any help.

解决方案

No idea how you got your results, since it would not sort by string value... You should reverse a1 and a2 in your example

Best way in any case (as per Mladen) is:

metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" => 10 }
metrics.sort_by {|_key, value| value}
  # ==> [["siteb.com", 9], ["sitec.com", 10], ["sitea.com", 745]]

If you need a hash as a result, you can use to_h (in Ruby 2.0+)

metrics.sort_by {|_key, value| value}.to_h
  # ==> {"siteb.com" => 9, "sitec.com" => 10, "sitea.com", 745}

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

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