Ruby 1.8:哈希#排序不返回哈希,但数组(更好的方式来做到这一点?) [英] Ruby 1.8: Hash#sort not return hash but array (better way to do this?)

查看:140
本文介绍了Ruby 1.8:哈希#排序不返回哈希,但数组(更好的方式来做到这一点?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby 1.8的某些场景中。如果我有一个散列

 #k是名字,v是order 
foo = {Jim=> 1,bar=> 1,joe=> 2}
sorted_by_values = foo.sort {| a,b | a [1]< ==> b [1]}
#sorted_by_values是一个数组数组,它​​不再是哈希!
sorted_by_values.keys.join','

我的解决方法是使方法<$ c

  class Array 
def to_hash(&块)
散列[* self.collect {| k,v |
[k,v]
} .flatten]
结束
结束

然后我可以执行以下操作:

  sorted_by_values.to_hash.keys.join','

有没有更好的方法来做到这一点?

解决方案

哈希按照定义是无序的。不能有一个排序后的哈希值。您最好的选择是使用collect从已排序的数组中提取键,然后对结果进行连接。

  sortedByValues = foo .sort {| a,b | a [1]< ==> b [1]} 
sortedByValues.collect {| a | a [0]} .join','


In some scenario of Ruby 1.8. If I have a hash

# k is name, v is order
foo = { "Jim" => 1, "bar" => 1, "joe" => 2}
sorted_by_values = foo.sort {|a, b| a[1] <==> b[1]}
#sorted_by_values is an array of array, it's no longer a hash!
sorted_by_values.keys.join ',' 

my workaround is to make method to_hash for Array class.

class Array
  def to_hash(&block)
    Hash[*self.collect { |k, v|
      [k, v]
    }.flatten]
  end
end

I can then do the following:

sorted_by_values.to_hash.keys.join ','

Is there a better way to do this?

解决方案

Hashes are unordered by definition. There can be no such thing as a sorted Hash. Your best bet is probably to extract the keys from the sorted array using collect and then do a join on the result

sortedByValues = foo.sort {|a, b| a[1] <==> b[1]}
sortedByValues.collect { |a| a[0] }.join ','

这篇关于Ruby 1.8:哈希#排序不返回哈希,但数组(更好的方式来做到这一点?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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