ruby 如何从ruby中的Hash获取前n个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8580497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get first n elements from Hash in ruby?
提问by harshit
I have a Hash and i have sorted it using the values
我有一个哈希,我已经使用这些值对它进行了排序
@friends_comment_count.sort_by{|k,v| -v}
Now i only want to get hash of top five elements .. One way is to use a counter and break when its 5. What is preferred way to do in ruby ?
现在我只想获得前五个元素的散列.. 一种方法是使用计数器并在其为 5 时中断。在 ruby 中做什么的首选方法是什么?
Thanks
谢谢
回答by Marek P?íhoda
h = { 'a' => 10, 'b' => 20, 'c' => 30 }
# get the first two
p Hash[*h.sort_by { |k,v| -v }[0..1].flatten]
EDITED:
编辑:
# get the first two (more concisely)
p Hash[h.sort_by { |k,v| -v }[0..1]]
回答by Trinculo
Can't you just do something like:
你不能做这样的事情:
h = {"test"=>"1", "test2"=>"2", "test3"=>"3"}
Then if you wanted the first 2:
那么如果你想要前两个:
p h.first(2).to_h
Result:
结果:
=> {"test"=>"1", "test2"=>"2"}
回答by Mikey Hogarth
New to ruby myself (please be nice if I'm wrong guys!) but does this work?
我自己是 ruby 新手(如果我错了,请多多益善!)但这行得通吗?
@friends_comment_count.sort_by{|k,v| -v}.first 5
Works for me in IRB, if I've understood what you're trying to achieve correctly
在 IRB 中对我来说有效,如果我已经理解你想要正确实现的目标
回答by Oleg Mikheev
You can't sort a Hash and that's why sort_bydoes NOT sort your Hash. It returns a sorted Array of Arrays.
您无法对哈希进行排序,这就是为什么不对哈希进行排序的原因sort_by。它返回一个排序的数组数组。
回答by David Grayson
In Ruby 2.2.0 and later, Enumerable#max_bytakes an optional integer argument that makes it return an array instead of just one element. This means you can do:
在 Ruby 2.2.0 及更高版本中,Enumerable#max_by接受一个可选的整数参数,使其返回一个数组而不是一个元素。这意味着您可以:
h = { 'a' => 10, 'b' => 20, 'c' => 30 }
n = 2
p h.max_by(n, &:last).to_h # => {"b"=>20, "c"=>30}
回答by Zepplock
Hashes are not ordered by nature (even thought in Ruby implementation they are). Try geting converting your Hash to Array and get [0,4] out of it
散列不是按自然顺序排列的(即使在 Ruby 实现中也认为它们是)。尝试将您的哈希转换为数组并从中获取 [0,4]

