开发者

In Ruby, is there a way to use something like hash.each_with_index do |[k,v], i|?

Otherwise, it needs to be

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

and setting the k and v this way seems a bit clumsy. Can it be simpler or something like

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

?


In fact, yes! Use parentheses:

h = {:a => 1, :b => 2.2}
h.each_with_index do |(k, v), i|
  p k, v, i
end


The Inject call should get what you want, http://www.ruby-doc.org/core/classes/Enumerable.src/M001494.html check that and scroll to the Inject portion, should work like a charm!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜