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

Ruby

Ruby Problem Overview


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|

?

Ruby Solutions


Solution 1 - Ruby

In fact, yes! Use parentheses:

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

Solution 2 - Ruby

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnonopolarityView Question on Stackoverflow
Solution 1 - RubymolfView Answer on Stackoverflow
Solution 2 - RubyJake KalstadView Answer on Stackoverflow