在Ruby中,有没有一种方法可以使用hash.each_with_index做| [k,v],i |?

否则,它必须是

h = {:a => 1, :b => 2.2}
h.each_with_index do |pair, i|
  k = pair[0]; v = pair[1]
  p k, v, i
end

并以这种方式设置kv似乎有些笨拙。 会更简单还是类似

h.each_with_index do |[k,v], i|

?

nopole asked 2020-06-29T20:17:08Z
2个解决方案
101 votes

其实是的! 使用括号:

h = {:a => 1, :b => 2.2}
h.each_with_index do |(k, v), i|
  p k, v, i
end
molf answered 2020-06-29T20:17:22Z
1 votes

Inject调用应该得到您想要的内容,[http://www.ruby-doc.org/core/classes/Enumerable.src/M001494.html]检查并滚动到“ Inject”部分,应该像个魅力一样起作用!

Jake Kalstad answered 2020-06-29T20:17:42Z
translate from https://stackoverflow.com:/questions/6117559/in-ruby-is-there-a-way-to-use-something-like-hash-each-with-index-do-k-v-i