按值排序散列哈希值(并返回散列值,而不是数组) [英] Sorting Hash of Hashes by value (and return the hash, not an array)
问题描述
我有以下哈希:
user = {
'user'=> {
'title'=> {'weight'=> 1,....}
'body'=> {'weight'=> 4,....}
....
....
}
}
是否有可能让用户按照其子哈希的权重键排序?
我查看哈希。排序,但它看起来像它返回数组而不是我原来的散列排序。
Hash
es被排序,但是 Hash#sort
仍返回 Array
of 阵列
秒。想象一下!它确实意味着你可以在它上面建立你自己的排序方法。 class Hash
def sorted_hash(& amp ; block)
self.class [sort(& block)]#Hash [[[key1,value1],[key2,value2]]]
end
end
Hash
es在Ruby 1.8中未排序。如果你想要兼容Ruby 1.8,你可以使用ActiveSupport的 OrderedHash
。它的行为类似于1.9 - Hash
,因此您可以在其上定义相同的 sorted_hash
方法:
class ActiveSupport :: OrderedHash
def sorted_hash(&block)
self.class [sort(& block)]
end
end
hash = ActiveSupport :: OrderedHash.new
hash [b] =b
hash [a] =a
hash#=> {b=>b,a=>a} =>未排序
hash.sorted_hash#=> {a=>a,b=>b} =>排序!
您必须将 sorted_hash
方法复制到您的代码,因为它默认情况下不存在!
深度排序更新:
如果您想要排序除了哈希键以外,按如下方式将块传递给 sorted_hash
方法(假设从上面实现):
hash = ActiveSupport :: OrderedHash.new
hash [a] = {attr=> 2,...=> ...}
hash [b] = {attr=> 1,...=> ...}
#未分类。
hash
#=> {a=> {attr=>2,...=>...},b=> {attr=>1 ...=>...}}
#按attr键排序。 (假设每个值都是散列本身!)
hash.sorted_hash {| a,b | a [1] [attr] => b [1] [attr]}
#=> {b=> {attr=>1,...=>...},a=> {attr=>2 ...=>...}}
I have the following hash:
user = {
'user' => {
'title' => {'weight' => 1, .... }
'body' => {'weight' => 4, ....}
....
....
}
}
Is is possible to get the User sorted by the weight key of its child hashes?
I looked in the Hash.sort, but it looks like it returns array rather than my original hash sorted.
In Ruby 1.9, Hash
es are sorted, but Hash#sort
still returns an Array
of Array
s. Imagine that! It does imply that you can build your own sorting method on top of it.
class Hash
def sorted_hash(&block)
self.class[sort(&block)] # Hash[ [[key1, value1], [key2, value2]] ]
end
end
Hash
es are unsorted in Ruby 1.8. If you want Ruby 1.8 compatibility, you can use ActiveSupport's OrderedHash
. It behaves like a 1.9-Hash
, so you can define the same sorted_hash
method on it:
class ActiveSupport::OrderedHash
def sorted_hash(&block)
self.class[sort(&block)]
end
end
hash = ActiveSupport::OrderedHash.new
hash["b"] = "b"
hash["a"] = "a"
hash #=> {"b"=>"b", "a"=>"a"} => unsorted
hash.sorted_hash #=> {"a"=>"a", "b"=>"b"} => sorted!
You have to copy the sorted_hash
method to your code, because it does not exist by default!
Update for deep sorting:
If you're looking to sort on something else than the hash key, pass a block to the sorted_hash
method as follows (assuming the implementation from above):
hash = ActiveSupport::OrderedHash.new
hash["a"] = { "attr" => "2", "..." => "..." }
hash["b"] = { "attr" => "1", "..." => "..." }
# Unsorted.
hash
#=> {"a"=>{"attr"=>"2", "..."=>"..."}, "b"=>{"attr"=>"1", "..."=>"..."}}
# Sort on the "attr" key. (Assuming every value is a Hash itself!)
hash.sorted_hash { |a, b| a[1]["attr"] <=> b[1]["attr"] }
#=> {"b"=>{"attr"=>"1", "..."=>"..."}, "a"=>{"attr"=>"2", "..."=>"..."}}
这篇关于按值排序散列哈希值(并返回散列值,而不是数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!