如何迭代Ruby中的一部分哈希? [英] How to iterate over part of a hash in Ruby?
问题描述
h = Hash.new
(1..100).each { |v| h.store(v * 2, v*v) }
迭代的最佳方法是什么没有使用密钥的散列的给定部分?例如,从元素10到元素20?使用Ruby 1.9.3。
What is the best way to iterate over a given part of the hash without using the keys? For example, from element 10 to element 20? Using Ruby 1.9.3.
编辑 - 回应Dave的评论:
本来我想通过键访问数据(因此hash )。但我也想通过元素编号进行迭代。顺便说一句,每个元素都是一个散列。
EDIT - In response to Dave's comment:
Originally I wanted to access the data through keys (hence the hash). But I also want to iterate by element number. BTW, each element is a hash.
那么,什么是设计散列或散列数组散列哈希的最佳方式,可以通过元素数迭代或访问键?数据如下所示。缺少日期。
So, what is the best way to design a hash of hashes or array of hashes that can be iterated by element number or accessed by key? The data looks like the following. There are missing dates.
2011/6/23 - > 5,6,8,3,6
2011/6/26 - > 6,8,4,8,5
6/27/2011 - > 8,4,3,2,7
6/23/2011 -> 5, 6, 8, 3, 6
6/26/2011 -> 6, 8, 4, 8, 5
6/27/2011 -> 8, 4, 3, 2, 7
推荐答案
如果我明白你要求的是什么,你可以按如下方式迭代你的哈希部分。这为您提供了第1001到第2000个值:
If I understand what you're asking for, you can iterate over a portion of your hash as follows. This gives you the 1001st through 2000th values:
h.keys[1000..1999].each do |key|
# Do something with h[key]
end
这篇关于如何迭代Ruby中的一部分哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!