【发布时间】:2011-01-06 05:10:15
【问题描述】:
我可能遗漏了一些明显的东西,但是有没有办法在每个循环的哈希内访问迭代的索引/计数?
hash = {'three' => 'one', 'four' => 'two', 'one' => 'three'}
hash.each { |key, value|
# any way to know which iteration this is
# (without having to create a count variable)?
}
【问题讨论】:
-
匿名:不,哈希没有排序。
-
哈希在技术上没有排序,但在 ruby 中你可以在某种意义上对它们进行排序。 sort() 会将它们转换为已排序的嵌套数组,然后您可以将其转换回散列:your_hash.sort.to_h
标签: ruby enumerable